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 = ...
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
.
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.
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