- 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.
推薦閱讀
- Microsoft Dynamics 365 Extensions Cookbook
- Mastering Unity Shaders and Effects
- 量化金融R語言高級(jí)教程
- C語言程序設(shè)計(jì)
- Asynchronous Android Programming(Second Edition)
- 精通MATLAB(第3版)
- Apache Kafka Quick Start Guide
- Instant Lucene.NET
- Web性能實(shí)戰(zhàn)
- Go語言開發(fā)實(shí)戰(zhàn)(慕課版)
- Python數(shù)據(jù)可視化之美:專業(yè)圖表繪制指南(全彩)
- After Effects CC案例設(shè)計(jì)與經(jīng)典插件(視頻教學(xué)版)
- Mapping with ArcGIS Pro
- Python程序設(shè)計(jì)教程
- 軟件再工程:優(yōu)化現(xiàn)有軟件系統(tǒng)的方法與最佳實(shí)踐