- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 216字
- 2021-06-25 20:49:23
Null safety
Probably the most notorious exception in the Java world is NullPointerException.
The reason behind this exception is that every object in Java can be null. The code here shows us why:
String s = "Hello";
...
s = null;
System.out.println(s.length); // Causes NullPointerException
In this case, marking s as final would prevent the exception.
But what about this one:
public class Printer {
public static void printLength(final String s) {
System.out.println(s.length);
}
}
From anywhere in the code it's still possible to pass null:
Printer.printLength(null); // Again, NullPointerException
Since Java 8, there's been an optional construct:
if (optional.isPresent()) {
System.out.println(optional.get());
}
In a more functional style:
optional.ifPresent(System.out::println);
But... it doesn't solve our problem. We can still pass null instead of the proper Optional.empty() and crash the program.
Kotlin checks it even earlier—during compile time:
val s : String = null // Won't compile
Let's go back to our printLength() function:
fun printLength(s: String) {
println(s.length)
}
Calling this function with null won't compile any more:
printLength(null) // Null can not be a value of a non-null type String
If you specifically want your type to be able to receive nulls, you'll need to mark it as nullable using the question mark:
val notSoSafe : String? = null
- Vue.js設(shè)計(jì)與實(shí)現(xiàn)
- BeagleBone Media Center
- 面向STEM的Scratch創(chuàng)新課程
- Functional Programming in JavaScript
- JavaScript從入門(mén)到精通(第3版)
- Mastering Yii
- 精通MATLAB(第3版)
- Android程序設(shè)計(jì)基礎(chǔ)
- Hands-On Neural Network Programming with C#
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)項(xiàng)目化教程
- Scala Functional Programming Patterns
- Hands-On Robotics Programming with C++
- 微前端設(shè)計(jì)與實(shí)現(xiàn)
- 高效使用Greenplum:入門(mén)、進(jìn)階與數(shù)據(jù)中臺(tái)
- jQuery Mobile Web Development Essentials(Second Edition)