Jérémy Touati
07/27/2019, 6:18 PMclass Position(val x: Int, val y: Int) {
constructor(positionCode: String) {
// construct a position from code here
}
}
this yields an error as the secondary constructor must call the primary one with : this(...)
i don't see an easy way to achieve this, i could call a function in the parent call such as this(getCoordsFromCode(positionFromCode))
but it obviously won't work as the primary one expects two ints, and I don't think you can unpack an array into a function that isn't expecting vararg
i could obviously swap the constructors and have the parent constructor call be something like this(getCodeFromCoords(x, y))
, but I was wondering if I was missing something (and I'm pretty sure I am)Mark Murphy
07/27/2019, 6:27 PMcompanion object
and a factory function:
class Position(val x: Int, val y: Int) {
companion object {
fun fromCode(positionCode: String): Position {
// construct a position from code here
}
}
}
You can then call Position.fromCode()
to create a Position
given a position code.Adam Powell
07/27/2019, 6:29 PMfun Position(positionCode: String): Position {
// parse the position code
return Position(x, y)
}
class Position(val x: Int, val y: Int) {
// other class contents
}
Jérémy Touati
07/27/2019, 6:30 PMAdam Powell
07/27/2019, 6:31 PMkotlinx.coroutines
for Job()
Jérémy Touati
07/27/2019, 6:32 PMAdam Powell
07/27/2019, 6:34 PMMark Murphy
07/27/2019, 6:34 PMthis(getXFromCode(positionCode), getYFromCode(positionCode))
, requiring two parsing passes, which isn't idealAdam Powell
07/27/2019, 6:35 PMTypename.
to get an autocomplete list of options.listOf()
for an example of thatfun Foo.toBar(): Bar
or fun Foo.asBar(): Bar
is more idiomatic, respectivelyJérémy Touati
07/27/2019, 7:04 PMAdam Powell
07/27/2019, 7:05 PMJérémy Touati
07/27/2019, 7:06 PMPosition.
, I'm not expecting to find a top level function as a suggestionAdam Powell
07/27/2019, 7:08 PM.toFoo()
extensions; it's temporary as an audience learns the language but something to occasionally consider.Jérémy Touati
07/27/2019, 7:12 PM