我目前必须写
val myList: List<Int>? = listOf()
if(!myList.isNullOrEmpty()){
// myList manipulations
}
哪个智能广播myList不能为非null。以下没有提供任何智能广播:
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?
答案 0 :(得分:6)
此问题由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 {
returns(false) implies (this@isNullOrEmpty != null)
}