问题描述
Kotlin中没有 static
关键字。
There is no static
keyword in Kotlin.
表示<$ c的最佳方法是什么$ c> static Kotlin中的Java方法?
What is the best way to represent a static
Java method in Kotlin?
推荐答案
将函数放在伴侣对象中。
You place the function in the "companion object".
所以像这样的java代码:
So the java code like this:
class Foo {
public static int a() { return 1; }
}
将成为
class Foo {
companion object {
fun a() : Int = 1
}
}
然后你可以在Kotlin代码中使用它
You can then use it from inside Kotlin code as
Foo.a();
但是从Java代码中,您需要将其称为
But from within Java code, you would need to call it as
Foo.Companion.a();
(这也适用于Kotlin。)
(Which also works from within Kotlin.)
如果您不想指定 Companion
位,您可以添加 @JmmStatic
注释或为你的伴侣班命名。
If you don't like having to specify the Companion
bit you can either add a @JvmStatic
annotation or name your companion class.
来自:
class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}
可以通过使用类
名称作为限定符来调用伴随对象的成员:
Members of the companion object can be called by using simply the class name as the qualifier:
val instance = MyClass.create()
...
但是,在JVM上你可以拥有memb如果您使用 @JmmStatic
注释,则伴随对象的ers生成
作为真正的静态方法和字段。有关更多详细信息,请参阅Java互操作性部分。
However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the @JvmStatic
annotation. See the Java interoperability section for more details.
添加 @JmmStatic
注释看起来像这样
class Foo {
companion object {
@JvmStatic
fun a() : Int = 1;
}
}
然后它将作为真正的Java静态函数存在,从
可以访问Java和Kotlin Foo.a()
。
and then it will exist as a real Java static function, accessible fromboth Java and Kotlin as Foo.a()
.
如果它只是不喜欢 Companion
名称,那么你也可以
提供一个明确的名字对于伴侣对象看起来像这样:
If it is just disliked for the Companion
name, then you can alsoprovide an explicit name for the companion object looks like this:
class Foo {
companion object Blah {
fun a() : Int = 1;
}
}
这将允许你从Kotlin调用它方式,但是来自java的
,如 Foo.Blah.a()
(这也适用于Kotlin)。
which will let you call it from Kotlin in the same way, butfrom java like Foo.Blah.a()
(which will also work in Kotlin).
这篇关于什么是Kotlin中的Java静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!