Tuesday, 21 November 2017

Kotlin: nullable types

By default, kotlin reference types (Int, Float, Double, String etc.,) do not take null values. Kotlin introduced this feature to avoid null pointer exceptions.

Test.kt
fun main(args: Array<String>) {
 var name : String = "Krishna"
 
 name = null
}

When you try to compile above program, kotlin throws below error.
ERROR: Null can not be a value of a non-null type String (6, 9)

How can I define a variable that take null value?
By using nullable types, you can define a variable that takes null values. Append the ‘?’ to the reference type to take null values.

Type
Nullable type
Int
Int?
String
String?
Double
Double?
Person
Person?


Ex
 var id: Int? = 1
 var name: String? = "Krishna"
 var salary: Double? = 123.456
 var person: Person? = Person("Krishna")

 id = null
 name = null
 salary = null
 person = null



Previous                                                 Next                                                 Home

No comments:

Post a Comment