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

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.
主站蜘蛛池模板: 鄂托克旗| 资中县| 海原县| 鄂伦春自治旗| 东丽区| 昌黎县| 禄丰县| 南靖县| 介休市| 南康市| 鄂州市| 当阳市| 雅安市| 当阳市| 收藏| 侯马市| 商城县| 大冶市| 兖州市| 旺苍县| 阿坝县| 南华县| 潮州市| 曲周县| 营山县| 白河县| 庄浪县| 济源市| 大邑县| 太原市| 永泰县| 兴业县| 水富县| 静安区| 达拉特旗| 峨眉山市| 萨嘎县| 五大连池市| 台江县| 辉县市| 兖州市|