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

Code contracts

As smart as compilers are these days, there are scenarios that don't have enough context and yield compilation errors. However, those errors cannot possibly occur here. You might have come across functions similar, at least logically, to the following one:

data class Command(val timestamp:Long)

fun processCommand(command:Command?){
validate(command)
println(command.timestamp)
}

fun validate(command:Command?){
if(command == null) {
throw new IllegalArgumentException("Invalid 'command' parameter. Expecting non-null parameter")
}

//... more validation here
}

If you were to compile this code as it is, the compiler will return an error at println(command.type). It will say—Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Command?. Given the earlier validate method, we know the error can never occur.
Wouldn't it be nice if we have a way to inform the compiler that the validate function already checks for null and, therefore, avoid the compilation error? Since Kotlin 1.3, you can do exactly this through the use of the Contracts API. 

主站蜘蛛池模板: 肇庆市| 泾阳县| 花垣县| 瓦房店市| 泽库县| 方正县| 泗水县| 广昌县| 浮梁县| 屏东市| 广西| 邳州市| 宁强县| 安化县| 翁源县| 华坪县| 广灵县| 巴彦淖尔市| 沙湾县| 秀山| 泰州市| 读书| 汝城县| 察雅县| 杭锦旗| 古交市| 镇赉县| 弥勒县| 红桥区| 瑞昌市| 武平县| 罗城| 新干县| 永州市| 徐汇区| 大埔区| 璧山县| 竹溪县| 黄冈市| 正镶白旗| 凉城县|