Can I add companion extension without first having companion object within a class?

278 Views Asked by At

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())
1

There are 1 best solutions below

2
On

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()