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

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.
主站蜘蛛池模板: 隆德县| 七台河市| 建阳市| 青海省| 伽师县| 富源县| 宝丰县| 依兰县| 密云县| 白水县| 武邑县| 汉阴县| 余姚市| 佛学| 田阳县| 和顺县| 万州区| 华容县| 兴城市| 绩溪县| 淮阳县| 连山| 建阳市| 渑池县| 开江县| 哈密市| 门源| 太湖县| 江孜县| 象山县| 绥棱县| 修武县| 承德县| 宁夏| 恩平市| 华坪县| 弥渡县| 綦江县| 樟树市| 威信县| 长沙市|