且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Kotlin 中 Java 静态方法的等价物是什么?

更新时间:2022-06-08 18:22:58

您将函数放在伴随对象"中.

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).