kotlin合约的目的是什么

Bac*_*man 8 android kotlin

正在阅读apply函数代码源码,发现

contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
Run Code Online (Sandbox Code Playgroud)

并且合约有一个空的主体,实验性的

@ContractsDsl
@ExperimentalContracts
@InlineOnly
@SinceKotlin("1.3")
@Suppress("UNUSED_PARAMETER")
public inline fun contract(builder: ContractBuilder.() -> Unit) { }
Run Code Online (Sandbox Code Playgroud)

合同的真正目的是什么,是否会保留在下一个版本中?

Gio*_*oli 7

合同的真正目的是什么

Kotlin合约的真正目的是帮助编译器做出一些自己无法做出的假设。有时,开发人员比编译器更了解某个功能的用法,并且可以将特定的用法教给编译器。

callsInPlace既然你提到了,我就举个例子。

想象一下有以下功能:

fun executeOnce(block: () -> Unit) {
  block()
}
Run Code Online (Sandbox Code Playgroud)

并以这种方式调用它:

fun caller() {
  val value: String 
  executeOnce {
      // It doesn't compile since the compiler doesn't know that the lambda 
      // will be executed once and the reassignment of a val is forbidden.
      value = "dummy-string"
  }
}
Run Code Online (Sandbox Code Playgroud)

Kotlin合约在这里有帮助。您可以callsInPlace用来告诉编译器该 lambda 将被调用多少次。

@OptIn(ExperimentalContracts::class)
fun executeOnce(block: ()-> Unit) {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
}

@OptIn(ExperimentalContracts::class)
fun caller() {
  val value: String 
  executeOnce {
      // Compiles since the val will be assigned once.
      value = "dummy-string"
  }
}
Run Code Online (Sandbox Code Playgroud)

它会保留在下一个版本中吗?

Who knows. They are still experimental after one year, which is normal for a major feature. You can't be 100% sure they will be out of experimental, but since they are useful and they are here since one year, in my opinion, likely they'll go out of experimental.