在Kotlin中没有静态关键字。

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


当前回答

如果你需要一个函数或属性绑定到一个类,而不是它的实例,你可以在一个伴随对象中声明它:

class Car(val horsepowers: Int) {
    companion object Factory {
        val cars = mutableListOf<Car>()

        fun makeCar(horsepowers: Int): Car {
            val car = Car(horsepowers)
            cars.add(car)
            return car
        }
    }
}

伴生对象是一个单例对象,它的成员可以通过包含类的名称直接访问

val car = Car.makeCar(150)
println(Car.Factory.cars.size)

其他回答

有两种方法可以在Kotlin中应用静态

首先在类下创建一个伴生对象

为例:

class Test{
    companion object{
          fun isCheck(a:Int):Boolean{
             if(a==0) true else false
          }
     }
}

你可以称这个函数为

Test.Companion.isCheck(2)

另一种方法是创建一个对象类

object Test{
       fun isCheck(a:Int):Boolean{
            if(a==0) true else false
       }
}

编码快乐!

对于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 Foo{
   fun foo() = println("Foo")
   val bar ="bar"  
}

Foo.INSTANCE.foo()

您可以通过Companion Objects在Kotlin中实现静态功能

Adding companion to the object declaration allows for adding the static functionality to an object even though the actual static concept does not exist in Kotlin. A companion object can access all members of the class too, including the private constructors. A companion object is initialized when the class is instantiated. A companion object cannot be declared outside the class. class MyClass{ companion object { val staticField = "This is an example of static field Object Decleration" fun getStaticFunction(): String { return "This is example of static function for Object Decleration" } } }

伴侣对象的成员可以通过简单地使用类名作为限定符来调用:

输出:

MyClass.staticField // This is an example of static field Object Decleration

MyClass.getStaticFunction() : // This is an example of static function for Object Decleration

您可以使用Companion Objects - kotlinlang

它可以通过首先创建该接口来显示

interface I<T> {

}

然后我们必须在该接口内部创建一个函数:

fun SomeFunc(): T

然后,我们需要一节课:

class SomeClass {}

在该类中,我们需要一个伴生对象:

companion object : I<SomeClass> {}

在那个同伴对象中,我们需要旧的SomeFunc函数,但是我们需要重写它:

override fun SomeFunc(): SomeClass = SomeClass()

最后,在所有这些工作下面,我们需要一些东西来支持静态函数,我们需要一个变量:

var e:I<SomeClass> = SomeClass()