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

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.
主站蜘蛛池模板: 延津县| 固安县| 白城市| 乐至县| 锦屏县| 鹿邑县| 瑞金市| 响水县| 西贡区| 兰州市| 封丘县| 甘泉县| 东至县| 隆德县| 金溪县| 家居| 临澧县| 前郭尔| 梨树县| 晋中市| 株洲县| 博白县| 邢台市| 蓝田县| 克拉玛依市| 梁河县| 新源县| 化德县| 洮南市| 托克托县| 逊克县| 阜南县| 崇阳县| 石渠县| 镇远县| 德阳市| 全南县| 孝昌县| 永新县| 石家庄市| 五原县|