【发布时间】:2018-07-25 20:15:39
【问题描述】:
在doc,在Java中调用kotlin静态函数可以这样做:
class C {
companion object {
@JvmStatic fun foo() {}
fun bar() {}
}
}
C.foo(); // works fine
C.bar(); // error
C.INSTANCE.bar(); // works, a call through the singleton instance
C.INSTANCE.foo(); // works too
但对我来说,没有'companion',它就行不通,
kotlin 代码
class MyClass {
companion object {
@JvmStatic fun test(category: String, otherType: OtherType) {
... ...
}
}
}
在JAVA代码中调用静态test()函数,
MyClass.Companion.test("", OtherType()) //<== works
MyClass.test("", OtherType()) //<== error, "Cannot resolve method 'test(String, ..."
还有什么我可能错过的?
【问题讨论】:
-
无法重现这个...顺便说一下,您的示例有一个错误:您将
null传递为不可为空的OtherType。 -
感谢@Pawel,这只是我为失败案例输入的代码 sn-p,在实际代码中它不为空。
-
在你给出的例子中应该是
C.foo()、C.bar()等而不是Obj.foo()