Extension functions to Companion Objects appearance of Static functions

suggest change

If you want an extension that looks like a static function — for example, a fromString function on the class Something — the class must have a companion object, and the extension must be declared on that companion object:

class Something {
    companion object {}
}

class SomethingElse {
}

fun Something.Companion.fromString(s: String): Something = ... 

fun SomethingElse.fromString(s: String): SomethingElse = ... 

fun main(args: Array<String>) {
    Something.fromString("") //valid as extension function declared upon the
                             //companion object

    SomethingElse().fromString("") //valid, function invoked on instance not
                                   //statically

    SomethingElse.fromString("") //invalid
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents