Search code examples
kotlinnullnullablekotlin-null-safety

What is the difference between nullabe and non-nullable type in Kotlin


Please explain the difference between nullable and non-nullable type. I am new to kotlin and i am confused.
Thanks


Solution

  • Nullable types can hold nulls. When type is nullable the question mark is set after it's type:

    val str: String? = null
    

    Non-nullable types can't hold nulls:

    val str: String = "some value"
    

    If we try to set null value to Non-nullable type, IDE will give an error and code will not be compiled:

    val str: String = null // error, the code won't compile
    

    Here you can read more about Null Safety.