What is the purpose of kotlin contract

寵の児 提交于 2020-12-26 06:39:42

问题


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?


回答1:


What is the real purpose of contract

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.

I'll make an example with callsInPlace since you mentioned it.

Imagine to have the following function:

fun executeOnce(block: () -> Unit) {
  block()
}

And invoke it in this way:

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"
  }
}

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?

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.



来源:https://stackoverflow.com/questions/60958843/what-is-the-purpose-of-kotlin-contract

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!