

Kotlin also respects these annotations when they are present in Java code. Java compiler doesn’t use these annotations, but these annotations are used by IDEs, ORM libraries and other external tools to provide assistance while working with null values. length ) // Allowed (Prints null) Nullability AnnotationsĪlthough Java doesn’t support nullability in its type system, You can use annotations like and provided by external packages like, etc to mark a variable as Nullable or Not-null. toUpperCase ( ) ) // Allowed (Prints null) println (javaUser. Val javaUser = User ( null ) println (javaUser. So If you try to assign a null value to a regular variable, the compiler will throw an error. That means You have the ability to declare whether a variable can hold a null value or not.īy supporting nullability in the type system, the compiler can detect possible NullPointerException errors at compile time and reduce the possibility of having them thrown at runtime.Īll variables in Kotlin are non-nullable by default. Kotlin supports nullability as part of its type System. Well, Enter Kotlin! Nullability and Nullable Types in Kotlin Wouldn’t it be nice if we could detect possible NullPointerException exception errors at compile time itself and guard against them?

NullPointerExceptions are Runtime Exceptions which are thrown by the program at runtime causing application failure and system crashes. If you have been programming in Java or any other language that has the concept of null reference then you must have heard about or experienced NullPointerException in your programs. Sir Tony Hoare, The inventor of null reference This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler.

At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). It was the invention of the null reference in 1965. Nullable Types and Null Safety in Kotlin Rajeev Singh Kotlin Febru5 mins read
