Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin : null cannot be value of non null type kotlin

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

like image 217
Mohit Suthar Avatar asked Jan 27 '18 05:01

Mohit Suthar


People also ask

How do I assign a value to null in Kotlin?

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.

What type is null in Kotlin?

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.

How does Kotlin check not null?

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.

How do you handle null in Kotlin?

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.


2 Answers

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.

like image 189
Avijit Karmakar Avatar answered Oct 13 '22 17:10

Avijit Karmakar


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.

like image 16
s1m0nw1 Avatar answered Oct 13 '22 16:10

s1m0nw1