Reputation: 60081
For the below code, I can add invoke
extension to the Companion
operator fun MyValue.Companion.invoke(value: Int) =
MyValue(value.toString())
class MyValue(private val value: String) {
companion object
fun print() = println("value = $value")
}
This enable me to call something as below
MyValue(1).print()
But as you see originally MyValue
don't need the companion object
.
I wonder if MyValue
is without the companion object
, i.e.
class MyValue(private val value: String) {
fun print() = println("value = $value")
}
Is it possible for me to still create a Companion extension function? e.g.
operator fun MyValue.Companion.invoke(value: Int) =
MyValue(value.toString())
Upvotes: 2
Views: 345
Reputation: 2629
You can add a secondary constructor to your class that accept an Int,
class MyValue(private val value: String) {
constructor(value: Int) : this(value.toString())
fun print() = println("value = $value")
}
Now you can call both, MyValue("10").print()
and MyValue(10).print()
Upvotes: 0