【问题标题】:why having @JvmStatic but calling from java still needs 'Companion'为什么有@JvmStatic但从java调用仍然需要'Companion'
【发布时间】: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()

标签: android kotlin


【解决方案1】:

注解@JvmStatic 告诉Kotlin 编译器为MyClass 类生成一个静态方法,因此MyClass.Companion.test(...)MyClass.test("", OtherType()) 都可以工作。

没有@JvmStatic,只有MyClass.Companion.test(...) 起作用,因为编译器不会生成MyClass.test(...)

【讨论】:

  • 问题是即使使用@JvmStatic 它仍然抱怨没有'Companion'部分。
  • 它是否适用于 test(...) 的不同签名?例如test(category: String, other: String)。也许OtherType 是问题所在。
【解决方案2】:

在另一个项目中遇到类似问题,但在删除该项目并重新克隆后,同步后问题就消失了。

【讨论】:

    猜你喜欢
    • 2015-08-15
    • 2014-06-19
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2011-04-05
    相关资源
    最近更新 更多