Companion 对象的扩展函数(静态函数的外观)

如果你想扩展一个类 - 如果你是一个静态函数,例如对于类 Something 添加静态外观函数 fromString,这只有在类有一个伴随对象且扩展函数已在伴随对象上声明时才有效 :

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
}