Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to initialize nullable fields in kotlin?

I have recently reviewed some kotlin codes, All nullable field initialized as null.

What is the difference between val x : String? = null and val x : String?

Should we initialize the nullable fields as null?

like image 582
Samet Baskıcı Avatar asked Nov 16 '18 07:11

Samet Baskıcı


People also ask

How do you handle nullable in Kotlin?

Use the ?: Elvis operator safe-call operator returns null . It's similar to an if/else expression, but in a more idiomatic way. If the variable isn't null , the expression before the ?: Elvis operator executes. If the variable is null , the expression after the ?: Elvis operator executes.

Do you have to initialize variables in Kotlin?

Kotlin does not require you to mention the type of a variable when declaring it (thanks to type inference). A variable val must be initialized in the same block of code in which it was declared.

What happens if you add null null in Kotlin?

Nullable and Non-Nullable Types in Kotlin – If we try to assign null to the variable, it gives compiler error.

How do you make a nullable class in Kotlin?

In kotlin, declaration of variable is different from java as kotlin is null safe language. You have to declare variable nullable. Only then its value can be null. To access nullable values you have to use !! or ? with variable names.


1 Answers

A property must be initialized. Therefore you have to do the initialization var x : String? = null. Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String?.

Alternatively you can use lateinit, also on non-nullable types. But this has the effect, that it's not null, but uninitialized lateinit var x : String.

like image 119
tynn Avatar answered Oct 18 '22 12:10

tynn