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

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.

主站蜘蛛池模板: 淮阳县| 云霄县| 扶余县| 米脂县| 永州市| 伊川县| 洪洞县| 玉树县| 桂平市| 阿拉善左旗| 奈曼旗| 台江县| 泸州市| 安溪县| 白水县| 广昌县| 长武县| 库伦旗| 郯城县| 宝鸡市| 淮安市| 奈曼旗| 潢川县| 新源县| 苏州市| 双峰县| 织金县| 鞍山市| 威海市| 泌阳县| 四会市| 西吉县| 馆陶县| 灵石县| 五寨县| 石家庄市| 德保县| 即墨市| 建阳市| 弋阳县| 安乡县|