我现在不得不写
val myList: List<Int>? = listOf()
if(!myList.isNullOrEmpty()){
// myList manipulations
}它将myList智能广播为no非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()
}有没有办法获得自定义扩展的smartCasts?
发布于 2019-08-27 16:09:51
这是由Kotlin 1.3中引入的contracts解决的。
契约是一种通知编译器某些函数属性的方法,这样它就可以执行一些静态分析,在本例中启用智能强制转换。
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)
}https://stackoverflow.com/questions/57670014
复制相似问题