小编rex*_*ar5的帖子

Kotlin 合约不适用于扩展函数中的空检查

我正在尝试编写一个扩展函数,true如果值不null为 0 则返回,并使用契约向编译器保证,如果我返回true,则该值不为空。但是,它似乎不适用于智能投射。当我尝试将值传递给采用非 nullable 的函数时,它仍然无法编译Long

我尝试编译这段代码,但它不起作用。我希望将 a从 aid智能转换为a ,因为合约保证如果返回则传入的值不为空。LongLong?isValidIdtrueLong?

正如您所看到的,该属性是不可变的,所以我认为这不是问题。我还在下面添加了更多代码,因为问题似乎特定于扩展函数。当我将 ID 作为传统参数传递时它会起作用。

fun test() {
    val id: Long? = null //5L
    if (id.isValidID()) {
      // It won't compile because the compiler says that id is a Long?
      // instead of smart casting it to a Long. doWithId requires a Long.
      doWithId(id) 
    }
  }

  fun doWithId(id: Long) {}

  @OptIn(ExperimentalContracts::class)
  fun Long?.isValidID(): Boolean {
    contract { returns(true) …
Run Code Online (Sandbox Code Playgroud)

kotlin kotlin-null-safety kotlin-contracts

9
推荐指数
1
解决办法
454
查看次数