- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 165字
- 2021-06-24 14:13:30
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.
- CMDB分步構建指南
- 控糖控脂健康餐
- Getting Started with PowerShell
- R語言數據可視化實戰
- INSTANT Mercurial SCM Essentials How-to
- Visual Basic 6.0程序設計實驗教程
- 深入實踐DDD:以DSL驅動復雜軟件開發
- 貫通Tomcat開發
- Instant Automapper
- Python預測分析實戰
- Java高手是怎樣煉成的:原理、方法與實踐
- VMware vSphere 5.5 Cookbook
- 網絡綜合布線與組網實戰指南
- Java Web應用開發
- Instant SQL Server Analysis Services 2012 Cube Security