kotlin - 创建自定义扩展时保留 smartcast

标签 kotlin

我目前必须写

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/

相关文章:

generics - Kotlin泛型 “in”和 “out”在继承中的用法

android - 如何在 androidTest 范围内使用 kapt

java - 由于找不到 ALPN 处理器,与 WireMock 的集成测试失败

java - 如何在 Kotlin 中解析 JSON?

rest - 如何通过 Rest Service 使用 Kotlin/Jvm 将图像上传到 Parse Server?

kotlin - 我可以在Kotlin中访问 “enclosing”对象以进行内联函数调用吗?

kotlin - Arrow-Kt Fx 与 Kotlin 协程

gradle - 未模拟Kotlin Gradle DSL JSONObject

android - 获取 native 库的 native 地址时出错 : task_vision_jni_gms

android - 如何每分钟更新一个 Android 应用小部件