如果您要扩展类(如果您是静态函数),例如对于class Somethingadd static looking function 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("") //作为扩展函数在声明时有效 //伴随对象 SomethingElse().fromString("") //有效,在实例上调用的函数无效 //statically SomethingElse.fromString("") //invalid }