- 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.
- JavaScript全程指南
- C語言程序設計(第3版)
- Arduino by Example
- HTML5 移動Web開發從入門到精通(微課精編版)
- PowerCLI Cookbook
- Animate CC二維動畫設計與制作(微課版)
- Git高手之路
- Mastering Ext JS
- SAP BusinessObjects Dashboards 4.1 Cookbook
- Flutter跨平臺開發入門與實戰
- C語言程序設計教程
- Haskell Data Analysis Cookbook
- 微服務架構深度解析:原理、實踐與進階
- 持續輕量級Java EE開發:編寫可測試的代碼
- Raspberry Pi Robotic Projects(Third Edition)