我目前必须写
val myList: List<Int>? = listOf()
if(!myList.isNullOrEmpty()){
// myList manipulations
}
哪个智能广播 myList 为非空。以下不提供任何智能广播:
if(!myList.orEmpty().isNotEmpty()){
// Compiler thinks myList can be null here
// But this is not what I want either, I want the extension fun below
}
if(myList.isNotEmptyExtension()){
// Compiler thinks myList can be null here
}
private fun <T> Collection<T>?.isNotEmptyExtension() : Boolean {
return !this.isNullOrEmpty()
}
有没有办法为自定义扩展获取 smartCast?
最佳答案
这是由 contracts 解决的介绍于 Kotlin 1.3 .
契约是一种通知编译器函数的某些属性的方法,以便它可以执行一些静态分析,在这种情况下启用智能转换。
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
@ExperimentalContracts
private fun <T> Collection<T>?.isNotEmptyExtension() : Boolean {
contract {
returns(true) implies (this@isNotEmptyExtension != null)
}
return !this.isNullOrEmpty()
}
可以引用
isNullOrEmpty
的来源并看到类似的契约(Contract)。contract {
returns(false) implies (this@isNullOrEmpty != null)
}
关于kotlin - 创建自定义扩展时保留 smartcast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57670014/