Kotlin 中 Java 静态方法的等价物是什么? [英] What is the equivalent of Java static methods in Kotlin?

查看:37
本文介绍了Kotlin 中 Java 静态方法的等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin 中没有 static 关键字.

There is no static keyword in Kotlin.

在 Kotlin 中表示 static 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 位,您可以添加 @JvmStatic 注释或命名您的伴随类.

If you don't like having to specify the Companion bit you can either add a @JvmStatic annotation or name your companion class.

来自文档:

类中的对象声明可以用 companion 标记关键词:

Companion Objects

An object declaration inside a class can be marked with the companion keyword:

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 上,您可以生成伴随对象的成员作为真正的静态方法和字段,如果您使用 @JvmStatic注解.有关详细信息,请参阅 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.

添加@JvmStatic注解如下

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 from both Java and Kotlin as Foo.a().

如果只是不喜欢Companion这个名字,那么你也可以为伴随对象提供一个明确的名称,如下所示:

If it is just disliked for the Companion name, then you can also provide 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, but from java like Foo.Blah.a() (which will also work in Kotlin).

这篇关于Kotlin 中 Java 静态方法的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆