is this statement correct? i can actually access t...
# getting-started
e
is this statement correct? i can actually access the parameters within the class body
Copy code
class SmartTvDevice(deviceName: String, deviceCategory: String) : SmartDevice(deviceName, deviceCategory) {
    init {
        println("Device: $deviceName")
    }
}
i'm novice, i don't know if it has some other meaning or it is just a wrong sentence
j
> i can actually access the parameters within the class body The
init {}
block is special, because it has access to simple constructor parameters (not just class properties). It's the same for property initializers, and for the superclass constructor call (as in the example). The point is that you won't be able to access those constructor parameters in "regular" places of the class body: mostly the bodies of the methods of the class. In short, you won't be able to access these parameters in code that doesn't execute during the class construction (except if those values were captured by some lambda).
e
oh, thank you so much! i understand now :)
c
To further explain what Joffrey is saying:
Copy code
class Foo(value: Int) {

    init {
        println(value) // SPECIAL! allowed here
    }

    val bar = value // SPECIAL! allowed here

    val baz: Int
        get() = value // FORBIDDEN (it would need to be stored)

    fun foo() = value // FORBIDDEN (it would need to be stored)

}
If you want all of these to work, you only need to store the value. You can do this with just:
Copy code
class Foo(val value: Int) {
    // …everything the same…
}
This way, it can be accessed anywhere you want.
💯 1
e
In short, you won't be able to access these parameters in code that doesn't execute during the class construction
i'll keep this in mind
j
> i'll keep this in mind You don't have to remember the details around this. The compiler will tell you if you try to do something that's forbidden 🙂 But yeah the above might help you understand why the compiler complains in these cases.
1
e
thank you @CLOVIS, that helps a lot. i'll experiment with those 🙂
i'm new to slack, don't know how to reply in threads, sorry for the pings
@Joffrey thanks again
kodee welcoming 2
j
You are actually replying in the thread here, so all good 😉 (and indeed, no need for pings)
🙂 1