官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 博湖县| 陈巴尔虎旗| 利辛县| 左贡县| 本溪市| 额济纳旗| 和硕县| 永宁县| 华宁县| 北流市| 衡阳县| 溧阳市| 奈曼旗| 东乡| 嘉黎县| 固始县| 逊克县| 金坛市| 定西市| 奉节县| 辽源市| 丁青县| 朔州市| 黄石市| 汉阴县| 闸北区| 华蓥市| 瓦房店市| 永兴县| 锦屏县| 金湖县| 南宁市| 西昌市| 贵州省| 彰武县| 湘潭县| 泸溪县| 仁寿县| 白河县| 平昌县| 贵州省|