Kotlin : null cannot be value of non null type kotlin

Kotlin’s type system differentiates between nullable types and non-null types. For example, if you declare a simple String variable and let the compiler infer its type, it cannot hold null:

var a = "text" //inferred type is `String`
a = null //doesn’t compile!

On the other hand, if you want a variable to also be capable of pointing to null, the type is explicitly annotated with a question mark:

var a: String? = "text"
a = null //Ok!

In your example, the ArrayList is declared with the generic type CustomClass, which is not nullable. You need to use the nullable type CustomClass? instead. Also, you can make use of Kotlin’s standard library functions for creating instances of lists, preferably read-only ones.

var mList = listOf<CustomClass?>(null)

Otherwise mutableListOf() or also arrayListOf() will help you.


Then you have to write it in this way.

var mList = ArrayList<CustomClass?>()
mList.add(null)

You have to add a ? after the type in ArrayList because ? allows us to put a null value.