在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
当前回答
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
其他回答
很多人提到伴生对象,这是正确的。但是,正如你所知道的,你也可以使用任何类型的对象(使用对象关键字,而不是类),即,
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.
kotlin文档提供了三种方法, 第一个是在包中定义函数,没有类:
package com.example
fun f() = 1
第二个是使用@JvmStatic注释:
package com.example
class A{
@JvmStatic
fun f() = 1
}
第三个是使用伴侣对象
package com.example
clss A{
companion object{
fun f() = 1
}
}
这对我也有用
object Bell {
@JvmStatic
fun ring() { }
}
从芬兰湾的科特林
Bell.ring()
从Java
Bell.ring()
简单来说,你可以使用“同伴对象”进入Kotlin静态世界,比如:
companion object {
const val TAG = "tHomeFragment"
fun newInstance() = HomeFragment()
}
要创建一个常量字段,请使用代码中的“const val”。 但是尽量避免使用静态类,因为它会给使用Mockito进行单元测试带来困难。
我想对以上的回答做一些补充。
是的,你可以在源代码文件中定义函数(在类之外)。但是如果使用Companion Object在类中定义静态函数会更好,因为您可以通过利用Kotlin Extensions添加更多静态函数。
class MyClass {
companion object {
//define static functions here
}
}
//Adding new static function
fun MyClass.Companion.newStaticFunction() {
// ...
}
你可以调用上面定义的函数,就像你调用伴侣对象中的任何函数一样。