下面我有一些简单的东西(我使用when而不是if,因为我简化了一些使用when的代码)
fun simplePresent(presentable: Presentable?) {
when {
presentable != null -> execute(presentable)
else -> skip()
}
}
fun execute(presentable: Presentable) { // Do something }一切都很好。但是当我将签出代码重构为函数时
fun simplePresent(presentable: Presentable?) {
when {
hasPresentable(presentable) -> execute(presentable)
else -> skip()
}
}
fun execute(presentable: Presentable) { // Do something }
fun hasPresentable(presentable: Presentable?) = presentable != null传递给execute函数的值的智能强制转换为非null失败,从而导致报告required Presentable found Presentable?的编译时错误
我如何防止这个错误,同时我仍然保留我的重构代码?
发布于 2018-05-16 11:56:27
函数应该是相互独立的。如果presentable在类型级别不为空,则没有强制hasPresentable返回true的约束。
因此,如果没有Kotlin团队决定增强类型系统,这几乎是不可能的。
为什么不使用像presentable?.execute() ?: skip()这样的东西呢?
如果你想在hasPresentable中做更多的检查,你可以这样做:
fun checkPresentable(presentable: Presentable?): Presentable? =
presentable?.takeIf { do your check here }
fun simplePresent(presentable: Presentable?) =
checkPresentable(presentable)?.execute() ?: skip()
fun Presentable.execute() { }https://stackoverflow.com/questions/50362060
复制相似问题