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

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. 

主站蜘蛛池模板: 罗甸县| 凤山市| 承德市| 定西市| 义马市| 科技| 佛山市| 吴忠市| 威海市| 广水市| 油尖旺区| 新宁县| 云阳县| 阜新| 海盐县| 玉山县| 来凤县| 高州市| 武冈市| 西峡县| 南靖县| 马山县| 九龙城区| 特克斯县| 玛多县| 庄浪县| 从江县| 五莲县| 九江县| 安阳县| 新巴尔虎左旗| 克什克腾旗| 鱼台县| 右玉县| 平陆县| 共和县| 江山市| 万载县| 南和县| 班玛县| 蕉岭县|