Not nullable types (except corresponding to primitives) obviously can’t have default values.
Primitives theoretically can, but it seems to me better to write values explicitly:
var sum: Int
for (el in list) {
sum += el
}
Here
var sum = 0
will be much better!
The same with booleans.
As for the first example, ‘doneAsync’ is semantically mutable variable (like ‘v’ here):
val v: Boolean?
try {
doSmth(v) // If you’re able to use v with default ‘null’ value here
v = true // and reassign v here,
doSmth(v) // then ‘v’ behaves as a mutable variable, so it should be a var.
}
finally {
if (!v) {
}
}
val doneAsync = task(pageManager.getDom(tabId), it)
if (!doneAsync) {
it()
}
But I need to use try-finally. In Java I cannot use “final” modifier in this case (it is sad :)) and now I cannot do it in Kotlin. May be it is semantically correct, but really doneAsync is immutable (i.e. I must not modify it’s value). I don’t want change val to var only due to try-finally.