Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do optionals in Kotlin require explicit initialisation?

When defining an optional property in a class, Kotlin requires that it is explicitly initialised as null, like so:

var myString: String? = null

Is there any reason that the compiler cannot infer this initial value? I believe Swift would let you skip the = null part, however this is a compiler error in Kotlin. Wouldn't it be simpler to automatically have the value null after writing the following?

var myString: String?
like image 584
Andy Avatar asked Aug 18 '26 11:08

Andy


1 Answers

Explicitness is a part of the overall language design in Kotlin. There are no implicit defaults for any types in Kotlin language. There is also desire to discourage (mis)use of nulls, so in respect to initialization nulls are not considered special in any way. If you have a non-nullable string var myString: String they you are required to initialize it with something just like you are required to initialize a nullable string var myString: String? with something, so this way its initial value is always explicit.

Note, technically speaking, String? in Kotlin is not an optional string in Kotlin. In Kotlin it is called a nullable string. However, the most common use-case for nulls is to represent the "absence of value".

like image 166
Roman Elizarov Avatar answered Aug 20 '26 11:08

Roman Elizarov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!