I have a kotlin class with superclass: ```class My...
# getting-started
p
I have a kotlin class with superclass:
Copy code
class MyClass(param: SomeType): Base(param.somecalculation) {
  private final val calculated = param.somecalculation()
How to do somecalculation just once?
s
Copy code
fun MyClass(param: SomeType) = MyClass(param.someCalculation())

class MyClass(private val calculated: SomeCalculationResult): Base(calculated)
b
You could try something like:
Copy code
class MyClass(calculated: SomeCalculationResult): Base(calculated) {
    val calculated: SomeCalculationResult get() = super.calculated
}
p
@Sam unfortunately MyClass is a @Component annotated spring class, so I'm afraid I cannot make it work that way.
@Bogi Napoleon Wennerström maybe I can try with a
by lazy
property instead?
Well, my original snippet was not accurate. Instead of
param.somecalculation
there is
someFunction("param")
is more correct.
s
Can you make it a
@Bean
instead of a
@Component
?
Copy code
@Configuration
class MyClassConfiguration {
  @Bean fun myClass(param: SomeType) = MyClass(param.someCalculation())
}
p
Sure I can, but someCalculation should rather stick to MyClass, not the configuration (sorry for popping up with new requirements)
s
Can you modify the superclass?
If so, you could make this an abstract property rather than a constructor parameter
j
The requirements don't make sense to me. You want the calculation to happen in MyClass but to construct myClass you need to have already done the calculation! (Because base requires the precalculated value)
☝️ 1
🤔 1
m
What about something like this?
Copy code
class MyClass private constructor(
    val param: SomeType,
    val calculated: CalculationResult
): Base(calculated) {
    constructor(param: SomeType) : this(param, param.calculate())
}