1

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())
Elye
  • 53,639
  • 54
  • 212
  • 474
  • Related: [Is it possible to create extension constructors in Kotlin?](https://stackoverflow.com/questions/46582809/is-it-possible-to-create-extension-constructors-in-kotlin) – Ivo Nov 29 '22 at 09:53
  • Not possible. Think about the implementation - companion objects cannot be added *retroactively* to already compiled classes, whenever the compiler sees that you want to extend `Something.Companion`. – Sweeper Nov 29 '22 at 09:55
  • 2
    A similar feature is being prototyped https://youtrack.jetbrains.com/issue/KT-11968 – aSemy Nov 29 '22 at 11:58

1 Answers1

1

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

Mohamed Rejeb
  • 2,281
  • 1
  • 7
  • 16
  • I'm assuming I don't have access to the `MyValue` class, hence needing the extension function. I can also use `fun MyValue(value: Int) = MyValue(value.toString())`, but I want to see if we can extend a Companion function without originally having Companion within. – Elye Nov 29 '22 at 12:52
  • I don't think that so, `print` function requires `value` so this is not possible without companion object or extension function. – Mohamed Rejeb Nov 29 '22 at 12:58