- 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
- Boost.Asio C++ Network Programming(Second Edition)
- Web應用系統開發實踐(C#)
- Java程序設計實戰教程
- OpenCV 3和Qt5計算機視覺應用開發
- Servlet/JSP深入詳解
- HTML5+CSS3+JavaScript Web開發案例教程(在線實訓版)
- Node.js全程實例
- RISC-V體系結構編程與實踐(第2版)
- Raspberry Pi Home Automation with Arduino(Second Edition)
- Lift Application Development Cookbook
- jQuery從入門到精通(微課精編版)
- 會當凌絕頂:Java開發修行實錄
- Clojure Data Structures and Algorithms Cookbook
- Kotlin程序員面試算法寶典
- Learning ROS for Robotics Programming