- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 281字
- 2021-06-24 14:13:31
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.
- 多媒體CAI課件設計與制作導論(第二版)
- 從零構建知識圖譜:技術、方法與案例
- 國際大學生程序設計競賽中山大學內部選拔真題解(二)
- CockroachDB權威指南
- Java設計模式及實踐
- Expert Android Programming
- Python機器學習算法與實戰(zhàn)
- Learning Apache Mahout Classification
- Linux命令行與shell腳本編程大全(第4版)
- 量化金融R語言高級教程
- Android程序設計基礎
- Mastering openFrameworks:Creative Coding Demystified
- Babylon.js Essentials
- ASP.NET程序開發(fā)范例寶典
- Access 2010數據庫應用技術實驗指導與習題選解(第2版)