官术网_书友最值得收藏!

Contracts on method invocation

With the callsInPlace contract, which accepts a lambda argument, the compiler receives these guarantees:

  • The callable lambda won’t be invoked after the owner function is finished
  • It won’t be passed to another function without the contract

This is useful to restrict the call site where a provided lambda argument can be used. Consider the following code:

fun compute() {
val someValue: String

upperCase("kotlin is great") {
someValue = it
}
}

private fun upperCase(str: String, callback: (String) -> Unit) {
callback.invoke(str.toUpperCase())
}

If you compile it, you will receive an error like this—Captured values initialization is forbidden due to possible reassignment. What the compiler is saying is that it can’t ensure the callback function is invoked only once and it cannot, therefore, guarantee that the val variable is not assigned multiple times by the lambda.

This can be fixed by instructing the compiler that the callback function is invoked once and only once. Consider the following code:

@ExperimentalContracts
fun compute() {
val someValue: String

upperCase("kotlin is great") {
someValue = it
}
}

@ExperimentalContracts
private fun upperCase(str: String, callback: (String) -> Unit) {
contract {
callsInPlace(callback, InvocationKind.EXACTLY_ONCE)
}
callback.invoke(str.toUpperCase())
}

The contracts API defines four types of InvocationKind so you can give hints to the compiler and, therefore, benefit from the code contracts:

  • UNKNOWN: A function parameter is called in place, but it's unknown how many times it can be called.
  • EXACTLY_ONCE: A function parameter will be invoked exactly one time.
  • AT_LEAST_ONCE: A function parameter will be invoked one or more times.
  • AT_MOST_ONCE: A function parameter will be invoked one time or not invoked at all.
主站蜘蛛池模板: 扶绥县| 普陀区| 长岭县| 天等县| 岳阳县| 虎林市| 交口县| 新竹市| 策勒县| 石泉县| 郎溪县| 本溪市| 连江县| 嵩明县| 渝中区| 金山区| 莲花县| 攀枝花市| 澎湖县| 峡江县| 大新县| 吴堡县| 和顺县| 辉南县| 宁国市| 长泰县| 乳山市| 九龙坡区| 西青区| 临城县| 东莞市| 财经| 通州市| 泌阳县| 韶山市| 彰武县| 汉沽区| 阳泉市| 星座| 聂拉木县| 乐东|