Kotlin Extension functions to Companion Objects (appearance of Static functions)


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

    SomethingElse.fromString("") //invalid