https://kotlinlang.org logo
#announcements
Title
# announcements
k

karelpeeters

09/16/2017, 8:50 PM
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

diesieben07

09/16/2017, 8:50 PM
shudder
n

nil2l

09/16/2017, 8:54 PM
Yes, but you can’t share this computation between few parameters.
k

karelpeeters

09/16/2017, 8:55 PM
You can set properties from withing the
also
block and use those as parameters.
n

nil2l

09/16/2017, 8:55 PM
ctor(str: String): this(parse(str).s, parse(str).i)
Hm? Could you show example for primary constructor with two parameters?
d

diesieben07

09/16/2017, 8:59 PM
Guys... why not just write a factory method?
n

nil2l

09/16/2017, 9:00 PM
It was mentioned in the question as known solution.
aka static constructor.
d

diesieben07

09/16/2017, 9:01 PM
Yes, and my question is why not pick that solution instead of fighting with the language like this.
n

nil2l

09/16/2017, 9:04 PM
Just to sure I don’t miss something. Sometime Kotlin is very tricky! 🤖
d

diesieben07

09/16/2017, 9:04 PM
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

nil2l

09/16/2017, 9:06 PM
What do you mean? Common practice is
valueOf
,
fromFoo
.
d

diesieben07

09/16/2017, 9:08 PM
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

nil2l

09/16/2017, 9:10 PM
Oh.. thanks.