0 votes
in Kotlin by
What does ‘Null Safety’ mean in Kotlin?

3 Answers

0 votes
by

Null Safety feature allows removing the risk of occurrence of NullPointerException in real time. It is also possible to differentiate between nullable references and non-nullable references.

0 votes
by
Kotlin's type system is aimed at eliminating the danger of null references from code, also known as the The Billion Dollar Mistake.

One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception. In Java this would be the equivalent of a NullPointerException or NPE for short.

In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references). For example, a regular variable of type String can not hold null:

var a: String = "abc"

a = null // compilation error

To allow nulls, we can declare a variable as nullable string, written String?:

var b: String? = "abc"

b = null // ok

print(b)
0 votes
by

The types of systems that support Kotlin majorly distinguishes among the references that can carry nullable references, and the ones cannot carry nullable references. Kotlin is a null safety language aimed to eliminate the null pointer exception or null reference from the code, which is deliberately known as A Billion Dollar Mistake.

The most conventional stumbling block of many programming languages is that while accessing a member of a null reference, it results to be a NullPointerException, which could be because of !! operator or this constructor used somewhere else and passed at another point of code. The nullable property requires confirmation for the null check every time prior to its utilization.

In Kotlin, the system distinguishes between null references and not null references.

For example, a String variable cannot hold null:

For Example 5:

fun main(args: Array<String>){
    var x: String = "GURU99 is the only place where you will get maximum technical content!" // Not Null by default
    println("x is : $x")
    // You cannot assign null variable to not-nullable variables 
    // a=null // it will give compilation error
    var y: String? = "Thanks for visiting GURU99" 
// Nullable Variable
    println("y is : $y")
    y = null
    println("y is : $y")
}

Output:

Kotlin tutorial

Related questions

0 votes
asked May 26, 2022 in Kotlin by Robin
0 votes
0 votes
asked May 26, 2022 in Kotlin by Robin
...