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

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.

主站蜘蛛池模板: 六枝特区| 徐州市| 商南县| 屏南县| 石台县| 安溪县| 常州市| 沧源| 福建省| 徐闻县| 巩留县| 志丹县| 吉林市| 阳新县| 石首市| 微博| 怀来县| 高州市| 秦安县| 中卫市| 翁牛特旗| 晋城| 揭西县| 南开区| 柘荣县| 甘洛县| 两当县| 苗栗市| 涡阳县| 安多县| 青神县| 拉孜县| 武威市| 西平县| 青浦区| 丹凤县| 莎车县| 海城市| 壤塘县| 固安县| 湘潭县|