在Kotlin中没有静态关键字。

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


当前回答

使用对象表示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。

其他回答

简单来说,你可以使用“同伴对象”进入Kotlin静态世界,比如:

  companion object {
    const val TAG = "tHomeFragment"
    fun newInstance() = HomeFragment()
}

要创建一个常量字段,请使用代码中的“const val”。 但是尽量避免使用静态类,因为它会给使用Mockito进行单元测试带来困难。

对于Java:

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

等价的Kotlin代码:

object  Constants {
const val MAX_CLICK_INTERVAL: Long = 1000}

因此,等价于Java静态方法的是Kotlin中的对象类。

让,你有一个班级学生。你有一个静态方法getUniversityName()和一个静态字段totalStudent。

你应该在你的类中声明同伴对象块。

companion object {
 // define static method & field here.
}

然后你的类看起来像

    class Student(var name: String, var city: String, var rollNumber: Double = 0.0) {

    // use companion object structure
    companion object {

        // below method will work as static method
        fun getUniversityName(): String = "MBSTU"

        // below field will work as static field
        var totalStudent = 30
    }
}

然后你可以像这样使用那些静态方法和字段。

println("University : " + Student.getUniversityName() + ", Total Student: " + Student.totalStudent)
    // Output:
    // University : MBSTU, Total Student: 30

在Java中,我们可以这样写

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

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

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

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

使用@JVMStatic Annotation

companion object {

    // TODO: Rename and change types and number of parameters
    @JvmStatic
    fun newInstance(param1: String, param2: String) =
            EditProfileFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
}