在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
当前回答
这对我也有用
object Bell {
@JvmStatic
fun ring() { }
}
从芬兰湾的科特林
Bell.ring()
从Java
Bell.ring()
其他回答
很多人提到伴生对象,这是正确的。但是,正如你所知道的,你也可以使用任何类型的对象(使用对象关键字,而不是类),即,
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.
如果你需要一个函数或属性绑定到一个类,而不是它的实例,你可以在一个伴随对象中声明它:
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没有静态关键字——同伴对象的成员可以通过简单地使用类名作为限定符来调用:
package xxx
class ClassName {
companion object {
fun helloWord(str: String): String {
return stringValue
}
}
}
A.旧Java方式:
声明一个伴随对象来包含一个静态方法/变量 类Foo { 伴随对象{ fun foo() = println(" foo ") Val bar ="bar" } } 使用: Foo. Foo() //输出Foo println(Foo.bar) //输出bar
B.新的Kotlin方式
直接在文件上声明,而不需要在.kt文件上使用类。 fun foo() = println(" foo ") Val bar ="bar" 使用方法/变量的名称。(导入后) 使用: foo() //输出foo println(bar) //输出bar
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()
}
}
}