Normally you can't declare a var without assigning...
# getting-started
f
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
Your initial conception is not correct. The following works:
Copy code
val a: String
if (condition) {
    a = "foo"
} else {
    a = "bar"
}
🤔 1
Can you give a concrete example of code you are confused about?
f
Thanks. Why then in most cases the IDE complains?
image.png
d
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:
Copy code
val antani: String
init {
    antani = "ciao"
}
😀 1
f
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
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
Amazing replies, thank you so much
d
No problem 🙂