- 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.
- Django+Vue.js商城項目實戰
- Getting Started with Gulp(Second Edition)
- Java Web開發之道
- Vue.js快速入門與深入實戰
- FreeSWITCH 1.6 Cookbook
- Android 7編程入門經典:使用Android Studio 2(第4版)
- Cassandra Design Patterns(Second Edition)
- R用戶Python學習指南:數據科學方法
- ArcGIS for Desktop Cookbook
- 案例式C語言程序設計實驗指導
- Instant Debian:Build a Web Server
- Vue.js應用測試
- Unity 2018 Augmented Reality Projects
- Mastering Adobe Captivate 7
- 零基礎學C語言(第4版)