To actually answer your question, if the parent co...
# announcements
k
To actually answer your question, if the parent constructor has at least one parameter you can use this trick to run whatever code you want:
super(param.also { ... })
d
shudder
n
Yes, but you can’t share this computation between few parameters.
k
You can set properties from withing the
also
block and use those as parameters.
n
ctor(str: String): this(parse(str).s, parse(str).i)
Hm? Could you show example for primary constructor with two parameters?
d
Guys... why not just write a factory method?
n
It was mentioned in the question as known solution.
aka static constructor.
d
Yes, and my question is why not pick that solution instead of fighting with the language like this.
n
Just to sure I don’t miss something. Sometime Kotlin is very tricky! 🤖
d
Makes sense. 🙂
In my opinion a factory method is the best choice here, you can even make it look like a constructor call if you want to.
n
What do you mean? Common practice is
valueOf
,
fromFoo
.
d
A
operator fun invoke
in a
companion object
can be called like a constructor.
Some people don't like that practice, but I think it's nice.
n
Oh.. thanks.