Kotlin : null cannot be value of non null type kotlin

15,249

Solution 1

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.

Solution 2

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.

Share:
15,249
Mohit Suthar
Author by

Mohit Suthar

I don't want to love my Job, I love my work on Android. Bad habit on Kotlin I forgetting to JAVA

Updated on June 20, 2022

Comments

  • Mohit Suthar
    Mohit Suthar almost 2 years

    How to assign null value to ArrayList in Kotlin?

    I am trying to add null value to my custom ArrayList like that

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

    In java its possible but how can I achieve this in Kotlin? I am getting

    null cannot be value of non null type kotlin

    I need to insert null value for doing load more functionality in RecyclerView