Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//Null reference
var a: String = "abc"
a = null //compilation error
//output: Null can not be a value of a non-null type String
//Nullable operator ?
var a: String? = "abc"
a = null //ok
print(a)
//output: null
var a: String? = "abc"
a = null //ok
print(a.length) //compile error
//output: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
//Null-safety operator ?.
var a: String? = "abc"
a = null
print(a?.length) //ok
//output: null
// Not-null operator !!
var a: String? = "abc"
a = null
print(a!!.length)
/*output: Exception in thread "main" kotlin.KotlinNullPointerException
at FileKt.main (File.kt:9)
at FileKt.main (File.kt:-1)
at sun.reflect.NativeMethodAccessorImpl.invoke0 (NativeMethodAccessorImpl.java:-2)*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment