class MyObject(private val a: Int, private val b: Double) {
constructor(str: String) : this(parse(str))
companion object {
private fun parse(str: String): ???
}
}
Is there anything that would allow this to work? Currently I have to create 2 parse functions, one to get the first and another for the second value I need.
n
Nir
01/26/2021, 5:26 AM
A better option here is to get rid of the secondary constructor completely
Nir
01/26/2021, 5:27 AM
And just have a free function instead
Nir
01/26/2021, 5:27 AM
If you really want it to be invoked like a constructor then you could write it as an operator invoke of the companion object
Nir
01/26/2021, 5:28 AM
Basically change parse to operator invoke and have it return MyObject
e
ephemient
01/26/2021, 5:41 AM
you can also name a function the same as the object, e.g.
fun MyObject(...)
. this is what stdlib does for
List()
and a few others
a
Andrew
01/26/2021, 6:46 AM
I never tried this but it looks like I can omit the primary constructor and just have 2 that do exactly what I need