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

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
主站蜘蛛池模板: 贵德县| 盐边县| 泸定县| 泽库县| 旺苍县| 滁州市| 浑源县| 凤冈县| 临澧县| 垣曲县| 渭源县| 宜良县| 吉安县| 伽师县| 枣强县| 江安县| 象山县| 万山特区| 襄汾县| 武威市| 建昌县| 麻江县| 马公市| 鄂伦春自治旗| 马公市| 朝阳县| 咸丰县| 区。| 东阿县| 巴南区| 吉林省| 霍林郭勒市| 江北区| 盖州市| 武夷山市| 紫金县| 裕民县| 虞城县| 合肥市| 常熟市| 鞍山市|