I don't have to initialize a property right away i...
# getting-started
f
I don't have to initialize a property right away if I use
lateinit
or override the
getter
. Any other ways to get around immediate initialization? (It's a theoretical question)
n
does
by lazy
count? Which is a delegate 👇
👍 1
r
Using a delegate
f
thank you I'll have to look up what that is
nothing else?
y
if you have a
val
you can initialize it inside the constructor (after some logic) so its kind of obrigatory lazy non lazy haha
f
I see, thanks a lot
they can also be initialized in
init
blocks, right?
r
The
init
blocks are the constructor (basically).
1
f
If I put an init block directly under a property I can initialize it there
is there something similar for secondary constructors?
the difference to Java is confusing me so maybe what I write doesn't make much sense
r
Secondary constructors will run after the primary constructor (if one exists):
Copy code
class Thing(a: Int) {
    constructor(a: String) : this(a.length) {
        println(a)
    }

    init {
        println(a)
    }
}

Thing("thing")  // Will print "5" then "thing"
Basically, you need to ensure all properties are properly initialized no matter which constructor is called, which is why they are usually initialized in the primary constructor. You can, however, have a class without a primary constructor, in which case you can initialize the properties in the bodies of the secondary constructors:
Copy code
class Thing {
    val s: String
    val i: Int

    constructor(a: String) {
        s = a
        i = a.length
    }

    constructor(a: Int) {
        i = a
        s = ".".repeat(a)
    }
}
f
Thanks, exactly what I wanted to know