- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 161字
- 2021-06-24 14:13:31
Contracts API
Given the preceding code, let's put the new functionality to good use. All we need to do is annotate the validate method with @ExperimentalContracts and add the code at the beginning of the method body:
contract {
returns() implies (command != null)
}
The new code now looks like this:
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
data class Command(val timestamp: Long)
@ExperimentalContracts
fun processCommand(command: Command?) {
validate(command)
println(command.timestamp)
}
@ExperimentalContracts
fun validate(command: Command?) {
contract {
returns() implies (command != null)
}
if (command == null) {
throw IllegalArgumentException("Invalid 'command' parameter. Expecting non-null parameter")
}
//... more validation here
}
With the changes in place, the compiler will not raise a compilation error anymore.
The general syntax for a code contract is as follows:
fun ... {
contract {
Effect
}
}
Effect is an interface that encapsulates the effect of invoking the function. It goes without saying, calling the function through reflection will not benefit from the Contracts API.
推薦閱讀
- Angular UI Development with PrimeNG
- Mastering Objectoriented Python
- 零基礎玩轉區塊鏈
- React.js Essentials
- Instant QlikView 11 Application Development
- 嚴密系統設計:方法、趨勢與挑戰
- HTML5從入門到精通 (第2版)
- RSpec Essentials
- Mastering ArcGIS Enterprise Administration
- Python Essentials
- Managing Microsoft Hybrid Clouds
- Arduino Wearable Projects
- Python第三方庫開發應用實戰
- Python數據可視化之matplotlib實踐
- Spring MVC Blueprints