Kotlin合约的目的是什么 [英] What is the purpose of kotlin contract
问题描述
正在阅读应用功能代码源并找到
Was reading the apply function code source and found
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
合同中有一个空的实验性
and contract has an empty body, experimental
@ContractsDsl
@ExperimentalContracts
@InlineOnly
@SinceKotlin("1.3")
@Suppress("UNUSED_PARAMETER")
public inline fun contract(builder: ContractBuilder.() -> Unit) { }
合同 的真正目的是什么?在以后的版本中会保留吗?
what is the real purpose of contract and is it here to stay in the next versions?
推荐答案
合同的真正目的是什么
What is the real purpose of contract
Kotlin 合同的真正目的是帮助编译器做出一些其本身无法做出的假设.有时,开发人员比编译器更了解某个功能的用法,并且可以向编译器教授特定用法.
The real purpose of Kotlin contracts is to help the compiler to make some assumptions which can't be made by itself. Sometimes the developer knows more than the compiler about the usage of a certain feature and that particular usage can be taught to the compiler.
自您提到以来,我将以callsInPlace
为例.
I'll make an example with callsInPlace
since you mentioned it.
想象一下具有以下功能:
Imagine to have the following function:
fun executeOnce(block: () -> Unit) {
block()
}
并以这种方式调用它:
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"
}
}
科特林合同在此提供帮助.您可以使用callsInPlace
告诉编译器有关lambda会被调用多少次.
Here Kotlin contracts come in help. You can use callsInPlace
to teach the compiler about how many times that lambda will be invoked.
@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"
}
}
这里是留在下一个版本中吗?
is it here to stay in the next versions?
谁知道.他们在一年后仍处于实验阶段,这是主要功能的正常现象.您不能100%确信它们将脱离实验性,但是我认为它们很有用并且已经存在一年了,我认为它们很可能会脱离实验性.
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.
这篇关于Kotlin合约的目的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!