Search code examples
androidkotlinnullkotlin-null-safety

Why we can set "var name = null" with no error


I just started learning Kotlin and I found a problem I can't understand about Null Safety in Kotlin. I read that variable can't hold null value.

So I made some test about this

var name:String = "Albert"
name = null //error

Until I try this

var name = null //with no error

I don't know why I can set var name = null with no error.


Solution

  • Setting value without mentioning a type as null means it is a nothing type.

    var item = null // "Nothing" type

    The above item is of Nothing? type