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

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. 

主站蜘蛛池模板: 红原县| 永登县| 霍山县| 阳江市| 依安县| 吉木乃县| 西峡县| 大埔区| 陇南市| 潮州市| 定安县| 安义县| 武安市| 汪清县| 儋州市| 德惠市| 开远市| 成武县| 分宜县| 宜章县| 鸡西市| 南漳县| 忻州市| 民权县| 武功县| 公主岭市| 黄梅县| 五华县| 河间市| 西华县| 崇阳县| 通海县| 博乐市| 虎林市| 阳山县| 安宁市| 报价| 阜阳市| 虞城县| 定安县| 蒙山县|