Extension functions to Companion Objects appearance of Static functions

suggest change

If you want to extend a class as-if you are a static function, for example for class Something add static looking function fromString, this can only work if the class has a companion object and that the extension function has been declared upon the 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