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

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.

主站蜘蛛池模板: 贺州市| 五台县| 灵台县| 蕲春县| 古蔺县| 池州市| 循化| 繁昌县| 钟山县| 鸡泽县| 绥中县| 沂南县| 綦江县| 桑日县| 凯里市| 拜城县| 循化| 贵州省| 上虞市| 肥东县| 方正县| 黄骅市| 南开区| 都兰县| 太白县| 恩平市| 鱼台县| 临邑县| 阿鲁科尔沁旗| 黑山县| 时尚| 石棉县| 海阳市| 吉林市| 富平县| 绥中县| 金乡县| 商南县| 寿宁县| 大竹县| 汾阳市|