https://kotlinlang.org logo
#getting-started
Title
# getting-started
p

Pihentagy

04/02/2024, 9:11 AM
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

Sam

04/02/2024, 9:19 AM
Copy code
fun MyClass(param: SomeType) = MyClass(param.someCalculation())

class MyClass(private val calculated: SomeCalculationResult): Base(calculated)
b

Bogi Napoleon Wennerström

04/02/2024, 10:35 AM
You could try something like:
Copy code
class MyClass(calculated: SomeCalculationResult): Base(calculated) {
    val calculated: SomeCalculationResult get() = super.calculated
}
p

Pihentagy

04/02/2024, 10:51 AM
@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

Sam

04/02/2024, 11:06 AM
Can you make it a
@Bean
instead of a
@Component
?
Copy code
@Configuration
class MyClassConfiguration {
  @Bean fun myClass(param: SomeType) = MyClass(param.someCalculation())
}
p

Pihentagy

04/02/2024, 11:20 AM
Sure I can, but someCalculation should rather stick to MyClass, not the configuration (sorry for popping up with new requirements)
s

Sam

04/02/2024, 11:32 AM
Can you modify the superclass?
If so, you could make this an abstract property rather than a constructor parameter
j

Jacob

04/02/2024, 12:05 PM
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

Matthew Feinberg

04/03/2024, 3:33 AM
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())
}