https://kotlinlang.org logo
Title
f

febs

11/26/2018, 12:50 PM
Normally you can't declare a var without assigning it a value; unless you state that it is a "lateinit" var. You can't declare a val withoutu assigning it a value too; but you can use "by lazy" to achieve that. BUT THEN Why in a { catch (e: Exception) } block I am allowed to define a val or a var and then assign it afterwards, without the need of "lateinit" nor "by lazy"?
d

diesieben07

11/26/2018, 12:52 PM
Your initial conception is not correct. The following works:
val a: String
if (condition) {
    a = "foo"
} else {
    a = "bar"
}
🤔 1
Can you give a concrete example of code you are confused about?
f

febs

11/26/2018, 12:54 PM
Thanks. Why then in most cases the IDE complains?
d

diesieben07

11/26/2018, 12:54 PM
That looks like a property. In that case you will have to put the initialization code inside an
init { }
block (or constructor), since you can't just write inside the class body.
So:
val antani: String
init {
    antani = "ciao"
}
😀 1
f

febs

11/26/2018, 12:56 PM
OK, thanks: so the behavior is different whether we are talking about a property or a "normal" var or val, right? If I got that correct, I'll dive deeper in that.
d

diesieben07

11/26/2018, 12:56 PM
What you call "normal" are local variables (inside function).
This has nothing to do with the initialization of val/var. It's just that you can't just have code inside a class body.
If you want initialization code for the instances of the class, you use the constructor or
init
.
In your code example the problem is not with the property, it is that your
antani = "ciao"
code cannot be put at that place.
f

febs

11/26/2018, 1:13 PM
Amazing replies, thank you so much
d

diesieben07

11/26/2018, 1:14 PM
No problem 🙂