eax
08/12/2024, 8:34 AMeax
08/12/2024, 8:34 AMclass SmartTvDevice(deviceName: String, deviceCategory: String) : SmartDevice(deviceName, deviceCategory) {
init {
println("Device: $deviceName")
}
}
eax
08/12/2024, 8:36 AMJoffrey
08/12/2024, 8:37 AMinit {}
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).eax
08/12/2024, 8:42 AMCLOVIS
08/12/2024, 8:42 AMclass 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:
class Foo(val value: Int) {
// …everything the same…
}
This way, it can be accessed anywhere you want.eax
08/12/2024, 8:42 AMIn short, you won't be able to access these parameters in code that doesn't execute during the class constructioni'll keep this in mind
Joffrey
08/12/2024, 8:45 AMeax
08/12/2024, 8:46 AMeax
08/12/2024, 8:48 AMeax
08/12/2024, 8:48 AMJoffrey
08/12/2024, 8:54 AM