在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
当前回答
您可以通过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
其他回答
使用对象表示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。
Docs建议使用包级函数来解决静态函数的大部分需求。它们只是在源代码文件中的类之外声明的。文件的包可以在文件的开头用关键字package指定。
宣言
package foo
fun bar() = {}
使用
import foo.bar
另外
import foo.*
你现在可以调用函数:
bar()
或者不使用import关键字:
foo.bar()
如果不指定包,则可以从根目录访问该函数。
如果您只有java经验,这可能看起来有点奇怪。原因是kotlin不是严格的面向对象语言。你可以说它支持类之外的方法。
编辑: 他们编辑了文档,不再包含关于推荐包级函数的句子。这是上面提到的原稿。
您可以通过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
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()
}
}
}