Elye
Elye

Reputation: 60081

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

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

Answers (1)

Mohamed Rejeb
Mohamed Rejeb

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

Related Questions