I've got a class that has a constructor with a sin...
# announcements
m
I've got a class that has a constructor with a single parameter and I want to add a couple of different "public" read only members to the class as well. there is a expensive algorithm to calculate the values of each of the members based on the constuctur parameters. How can I run the algorithm only once and populate vals?
d
Copy code
class MyClass(param1: String, param2: String) {
    val value1: ComputedThingy
    val value2: OtherComputedThingy
    
    init {
        value1 = TODO("heavy computation")
        value2 = TODO("more computation")
    }
m
ahh cool 🙂
c
why not
Copy code
class MyClass(param1: String, param2: String) {
    val value1 = TODO("heavy computation")
    val value2= TODO("more computation")
d
I assumed there is some commonality to the computation, which should not be done for each property
If that is not the case, do what Christoph said, yes
m
yeah but that is the case
n
Yeah, this "commonality" case makes init blocks so nice. I miss this feature in C++ quite a bit on occasion.
c
it would be cool if variables from the init block would be available in the body then you could do
Copy code
class MyClass(param1: String, param2: String) {
init {val heavy=heavy()}
    val value1 = heavy.one
    val value2= heavy.other
i sometimes do
Copy code
class MyClass(param1: String, param2: String) {
private val heavy=heavy()
    val value1 = heavy.one
    val value2= heavy.other
or if its more complex:
Copy code
class MyClass(param1: String, param2: String) {
private val heavy= run {
...
heavy() } 
    val value1 = heavy.one
    val value2= heavy.other
m
what is the benefit of doing that, compared to
Copy code
val value1
val value2

init {
   value1 = ...
   ....
   value2 = ...
}
c
not having to specify the type
m
ah!
correct, my example did miss that part!
n
that's an interesting point christoph