- 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.
- 算法零基礎一本通(Python版)
- 構建移動網站與APP:HTML 5移動開發入門與實戰(跨平臺移動開發叢書)
- Learning SAP Analytics Cloud
- Java虛擬機字節碼:從入門到實戰
- 重學Java設計模式
- 基于Swift語言的iOS App 商業實戰教程
- 名師講壇:Spring實戰開發(Redis+SpringDataJPA+SpringMVC+SpringSecurity)
- Gradle for Android
- 移動界面(Web/App)Photoshop UI設計十全大補
- Extending Puppet(Second Edition)
- Developing SSRS Reports for Dynamics AX
- Hands-On Full Stack Development with Spring Boot 2.0 and React
- Hands-On GUI Programming with C++ and Qt5
- 動手打造深度學習框架
- Scratch從入門到精通