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
}