kotlinextension-methodscompanion-object

Kotlin Extension on a class without Companion object


I have a simple Kotlin class, that does not declare a companion object.

class Foo

I would love to create an extension for companion object, even if one is not specified. I do not want to create an empty companion object.

fun Foo.Companion.bar()

How?

EDIT

What is the difference between:

  1. Me adding an empty companion in Foo
  2. compiler adds an empty companion in Foo

?


Solution

  • I would love to create an extension for companion object, even if one is not specified.

    Why?

    How?

    You can't. An extension, by definition, is something that extends ... something. You can't extend a non-existent entity. Remember that extension functions are basically static functions that take an instance of the extending object as the first parameter. So your example:

    fun Foo.Companion.bar()
    

    Would translate to:

    public static void bar(Foo.Companion objectBeingExtended) { }
    

    How is that supposed to work if Foo.Companion doesn't exist?