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
In an effort to rid the world of NullPointerException , variable types in Kotlin don't allow the assignment of null . If you need a variable that can be null, declare it nullable by adding ? at the end of its type. Declares a non- null String variable.
Nullable and Non-Nullable Types in Kotlin – Kotlin type system has distinguish two types of references that can hold null (nullable references) and those that can not (non-null references). A variable of type String can not hold null. If we try to assign null to the variable, it gives compiler error.
You can use the "?. let" operator in Kotlin to check if the value of a variable is NULL. It can only be used when we are sure that we are refereeing to a non-NULL able value.
Kotlin has a safe call operator (?.) to handle null references. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With