Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a reference variable in Kotlin

Tags:

java

kotlin

In Java one can initialize a reference variable with null, for example a String variable can be initialized like so:

String str = null;

But in Kotlin, the point is to avoid using null as much as possible. So how can I initialize a property without using null

var str: String = ...
like image 263
Toni Joe Avatar asked Jun 26 '17 17:06

Toni Joe


2 Answers

user lateinit keywords.Need to use, and then initialize

private lateinit var str : String
fun myInit(){
    str = "something";
}

Note : that accessing the uninitialized lateinit property results in an UninitializedPropertyAccessException.

However, lateinit does not support basic data types, such as Int.

like image 141
doubleThunder Avatar answered Nov 05 '22 15:11

doubleThunder


The point in Kotlin isn't to never use null (and nullable types), but rather to use it safely with convenient language constructs instead of fearing it. While using non-nullable types as much as possible is ideal, you don't have to always avoid them, that's why the various null handling constructs (safe calls, the Elvis operator, etc) exist.

If you can delay creating your variable until you have something to assign to it, that's a solution. If you can't, then marking it nullable and assigning null to it is perfectly fine, because the compiler will protect you from doing dangerous things with it.

like image 42
zsmb13 Avatar answered Nov 05 '22 15:11

zsmb13