- 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.
- 程序員修煉之道:程序設計入門30講
- Debian 7:System Administration Best Practices
- DevOps for Networking
- C# Programming Cookbook
- Magento 2 Theme Design(Second Edition)
- iOS開發實戰:從零基礎到App Store上架
- Python王者歸來
- Monitoring Elasticsearch
- 零基礎學Python數據分析(升級版)
- R大數據分析實用指南
- Getting Started with React Native
- Java零基礎實戰
- JavaScript機器人編程指南
- 大學計算機基礎實驗指導
- C++程序設計教程