在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
在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)
其他回答
使用对象表示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中(丑陋):
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用于控制编译后的文件名,该文件名应该放在包名声明之前)。
您可以通过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
除了迈克尔安德森的回答,我在我的项目中有其他两种编码方式。
第一:
你可以把所有变量白到一个类。 创建一个名为Const的kotlin文件
object Const {
const val FIRST_NAME_1 = "just"
const val LAST_NAME_1 = "YuMu"
}
您可以在kotlin和java代码中使用它
Log.d("stackoverflow", Const.FIRST_NAME_1)
第二:
您可以使用Kotlin的扩展函数 创建了一个名为Ext的kotlin文件,下面的代码是Ext文件中的所有代码
package pro.just.yumu
/**
* Created by lpf on 2020-03-18.
*/
const val FIRST_NAME = "just"
const val LAST_NAME = "YuMu"
你可以在kotlin代码中使用它
Log.d("stackoverflow", FIRST_NAME)
您可以在java代码中使用它
Log.d("stackoverflow", ExtKt.FIRST_NAME);
在Java中,我们可以这样写
class MyClass {
public static int myMethod() {
return 1;
}
}
在Kotlin中,我们可以用下面的方式写
class MyClass {
companion object {
fun myMethod() : Int = 1
}
}
在Kotlin中,一个同伴被用作静态。