在Kotlin中没有静态关键字。

在Kotlin中表示静态Java方法的最佳方法是什么?


当前回答

在kotlin中没有静态关键字。如果你想遵循DRY, kotlin文档建议使用包级函数。 创建一个扩展名为.kt的文件,并将您的方法放在其中。

package p
    fun m(){
    //fun body
    }

编译后m将会有一个public static final void的签名

and

import p.m

其他回答

kotlin文档提供了三种方法, 第一个是在包中定义函数,没有类:

package com.example

fun f() = 1

第二个是使用@JvmStatic注释:

package com.example

class A{
@JvmStatic
fun f() = 1
}

第三个是使用伴侣对象

package com.example

clss A{
companion object{
fun f() = 1
}
}

我想对以上的回答做一些补充。

是的,你可以在源代码文件中定义函数(在类之外)。但是如果使用Companion Object在类中定义静态函数会更好,因为您可以通过利用Kotlin Extensions添加更多静态函数。

class MyClass {
    companion object { 
        //define static functions here
    } 
}

//Adding new static function
fun MyClass.Companion.newStaticFunction() {
    // ...
}

你可以调用上面定义的函数,就像你调用伴侣对象中的任何函数一样。

将它们直接写入文件。

在Java中(丑陋):

package xxx;
class XxxUtils {
  public static final Yyy xxx(Xxx xxx) { return xxx.xxx(); }
}

在芬兰湾的科特林:

@file:JvmName("XxxUtils")
package xxx
fun xxx(xxx: Xxx): Yyy = xxx.xxx()

这两段代码在编译后是相等的(甚至编译后的文件名file:JvmName用于控制编译后的文件名,该文件名应该放在包名声明之前)。

在Java中,我们可以这样写

class MyClass {
  public static int myMethod() { 
  return 1;
  }
}

在Kotlin中,我们可以用下面的方式写

class MyClass {
  companion object {
     fun myMethod() : Int = 1
  }
}

在Kotlin中,一个同伴被用作静态。

很多人提到伴生对象,这是正确的。但是,正如你所知道的,你也可以使用任何类型的对象(使用对象关键字,而不是类),即,

object StringUtils {
    fun toUpper(s: String) : String { ... }
}

像使用java中的静态方法一样使用它:

StringUtils.toUpper("foobar")

That sort of pattern is kind of useless in Kotlin though, one of its strengths is that it gets rid of the need for classes filled with static methods. It is more appropriate to utilize global, extension and/or local functions instead, depending on your use case. Where I work we often define global extension functions in a separate, flat file with the naming convention: [className]Extensions.kt i.e., FooExtensions.kt. But more typically we write functions where they are needed inside their operating class or object.