kotlin - 如何避免在 kotlin 中使用繁琐的 holder
问题描述
我必须处理以下java代码
abstract class ScriptResult {
void ifSuccess(Consumer<Object> block) {
}
void ifError(Consumer<Throwable> block) {
}
static class Success extends ScriptResult {
private final Object returnValue;
Success(Object returnValue) {
this.returnValue = returnValue;
}
@Override
void ifSuccess(Consumer<Object> block) {
block.accept(returnValue);
}
}
static class Error extends ScriptResult {
private final Throwable throwable;
Error(Throwable throwable) {
this.throwable = throwable;
}
@Override
void ifError(Consumer<Throwable> block) {
block.accept(throwable);
}
}
}
我的 kotlin 测试使用以下断言助手:
private lateinit var scriptResult: ScriptResult
inline fun <reified T : Throwable> shouldHaveThrown(): T {
scriptResult.ifSuccess { result ->
fail("should have thrown ${T::class.java.name}, but returned `$result´")
}
lateinit var holder: T // (1)
scriptResult.ifError { throwable ->
if (throwable is T) {
holder = throwable // (2)
} else {
fail("expected ${T::class.java.name} to be thrown, but threw `$throwable´")
}
}
return holder // (3)
}
断言助手是有效的。我可以这样使用它:
val thrown = execution.shouldHaveThrown<MissingMethodException>()
assertThat(thrown.message).contains("missedMethod")
但我怀疑有一种更惯用的方式来返回throwable
,shouldHaveThrown
然后返回(1)声明持有者,(2)分配它,(3)最终返回它。如何?
解决方案
推荐阅读
- asp.net-core - 使用 IdenityServer4 成功登录后重定向到 localhost Web 应用程序
- php - 使用 AJAX 更新 mysql 值表单复选框值
- tensorflow - 使用 tensorflow 不会减少 CTC 损失,而使用 Keras 会减少
- sql - BigQuery 中的 SUBSTRING_INDEX
- c# - Web Service 方法 - 无法序列化,因为它没有无参数构造函数
- postgresql - psycopg2 在 SELECT 语句中舍入我的浮点数
- jquery - 在所选单选按钮的相应文本字段前面添加唯一符号
- sql - 如何根据与其他商品一起出售的商品获取我的已售商品总和
- python - 来自 **sklearn** 的 TSNE 与 **mahalanobis** 指标
- javascript - 使用条带卡元素和 vue.js 打破了标签顺序