创建自定义扩展时保留智能广播

Ada*_*dam 3 kotlin

我目前必须写

val myList: List<Int>? = listOf()
if(!myList.isNullOrEmpty()){
    // myList manipulations
}
Run Code Online (Sandbox Code Playgroud)

哪个智能广播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()
}
Run Code Online (Sandbox Code Playgroud)

有没有办法为自定义扩展获取smartCast?

Geo*_*ung 6

这可以通过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()
}
Run Code Online (Sandbox Code Playgroud)

您可以参考的来源isNullOrEmpty并看到类似的合同。

contract {
    returns(false) implies (this@isNullOrEmpty != null)
}
Run Code Online (Sandbox Code Playgroud)