therealbluepandabear
02/06/2022, 2:52 AMval myVar1: Any
2️⃣
var myVar2: Any? = null
3️⃣
lateinit var myVar3: Any
----
Also I have a minor question:
I'm confused, because I never knew that you could just write val x: Int
without initializing a value for x
?
Does the first option just compile to var x: Int? = null
?
Also how does this compile if it's a val
?
val myVar1: Any
myVar1 = 4
ephemient
02/06/2022, 3:46 AMclass X {
val a: Int = foo()
val b: Int = 42
fun foo(): Int = b
}
X().a // => 0
https://youtrack.jetbrains.com/issue/KT-10455
I think it's probably not resolvable without switching to a fundamentally different initialization model incompatible with Java thoughJoffrey
02/06/2022, 1:04 PMval
without initializer). I never needed it, and it unnecessarily separates initialization from declaration. Kotlin's if
and when
expressions allow to easily avoid the classic "declaration first + initialization in branches". You can just initialize directly. If it's too complicated, extract a function that computes and returns the value, and do val x = computeX()
.
Also, val
in general is preferable to var
if you don't really need to change the variable through the course of its life. The stdlib's function collection operations and the `if`/`when` expressions allow to avoid most var
usages.
As for 2️⃣ vs 3️⃣, they are not exactly the same.
Option 2️⃣ is more type-safe for the use site, it doesn't "lie" about anything. You have a value that can be null or not, and you have to check for null whenever you access it. You can also set the variable back to null at anytime too, which cannot be done in 3️⃣.
Option 3️⃣ is for cases where you know that you will initialize the variable to a non-null value before you will access it. It's mostly to avoid the inconvenience of checking for null every time is accessed, but it's a bit more dangerous because now the type is sort of "lying" about the nullability of the variable. I'd say it's mostly for cases where the compiler cannot know about the lifecycle of your component because the initialization order is guaranteed by some framework (for instance android or spring), but it shouldn't be overused.ephemient
02/06/2022, 1:14 PMJoffrey
02/06/2022, 1:37 PMKlitos Kyriacou
02/06/2022, 2:35 PMval result: Double
val duration = measureTime {
result = longCalculation()
}
Joffrey
02/06/2022, 4:39 PMmeasureTimedValue
thoughephemient
02/06/2022, 9:58 PMval (duration, value) = measureTimedValue { ... }
doesn't work at top- or class-levelJoffrey
02/06/2022, 11:01 PM