创建自定义扩展时保留 smartcast

2023-12-30

我目前必须写

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?


这是通过以下方式解决的合同 https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.contracts/index.html引入于科特林 1.3 https://kotlinlang.org/docs/reference/whatsnew13.html#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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建自定义扩展时保留 smartcast 的相关文章

随机推荐