在Kotlin中没有静态关键字。

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


当前回答

简单地使用这种方法

object Foo{
   fun foo() = println("Foo")
   val bar ="bar"  
}

Foo.INSTANCE.foo()

其他回答

object objectName {
    fun funName() {

    }
}

使用对象表示val/var/方法使静态。你也可以用object代替单例类。如果你想在类内部创建静态,你可以使用companion

object Abc{
     fun sum(a: Int, b: Int): Int = a + b
    }

如果你需要从Java调用它:

int z = Abc.INSTANCE.sum(x,y);

在Kotlin中,忽略INSTANCE。

对于Java:

public class Constants {
public static final long MAX_CLICK_INTERVAL = 1000;}

等价的Kotlin代码:

object  Constants {
const val MAX_CLICK_INTERVAL: Long = 1000}

因此,等价于Java静态方法的是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.

java静态方法到kotlin等效方法的确切转换如下所示。例:这里util类有一个静态方法,它在java和kotlin中都是等效的。@JvmStatic的使用非常重要。

Java代码:

    class Util{
         public static String capitalize(String text){
         return text.toUpperCase();}
       }

芬兰湾的科特林代码:

    class Util {
        companion object {
            @JvmStatic
            fun capitalize(text:String): String {
                return text.toUpperCase()
            }
        }
    }