官术网_书友最值得收藏!

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
主站蜘蛛池模板: 罗源县| 靖宇县| 旌德县| 大庆市| 沙洋县| 漳浦县| 禹城市| 繁昌县| 邹城市| 聂荣县| 泸西县| 黑水县| 广丰县| 铜鼓县| 固阳县| 朔州市| 万荣县| 禄丰县| 玉山县| 凌海市| 客服| 浠水县| 明星| 龙陵县| 明光市| 岳阳市| 克什克腾旗| 贞丰县| 东台市| 洱源县| 金平| 东光县| 原阳县| 青神县| 宁强县| 临湘市| 电白县| 大方县| 明星| 元氏县| 多伦县|