在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
当前回答
有两种方法可以在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
}
}
编码快乐!
其他回答
object objectName {
fun funName() {
}
}
您可以通过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
在kotlin中没有静态关键字。如果你想遵循DRY, kotlin文档建议使用包级函数。 创建一个扩展名为.kt的文件,并将您的方法放在其中。
package p
fun m(){
//fun body
}
编译后m将会有一个public static final void的签名
and
import p.m
☺
对于Java:
public class Constants {
public static final long MAX_CLICK_INTERVAL = 1000;}
等价的Kotlin代码:
object Constants {
const val MAX_CLICK_INTERVAL: Long = 1000}
因此,等价于Java静态方法的是Kotlin中的对象类。
你把函数放在“同伴对象”中。
java代码是这样的:
class Foo {
public static int a() { return 1; }
}
将成为
class Foo {
companion object {
fun a() : Int = 1
}
}
然后,您可以在Kotlin代码中作为
Foo.a();
但是在Java代码中,您需要将其调用为
Foo.Companion.a();
(也可以在Kotlin内部工作。)
如果您不喜欢指定Companion位,您可以添加@JvmStatic注释或命名您的Companion类。
从文档中可以看出:
Companion Objects An object declaration inside a class can be marked with the companion keyword: class MyClass { companion object Factory { fun create(): MyClass = MyClass() } } Members of the companion object can be called by using simply the class name as the qualifier: val instance = MyClass.create() ... However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the @JvmStatic annotation. See the Java interoperability section for more details.
添加@JvmStatic注释如下所示
class Foo {
companion object {
@JvmStatic
fun a() : Int = 1;
}
}
然后它将作为一个真正的Java静态函数存在,从 Java和Kotlin的Foo.a()。
如果只是不喜欢Companion名称,那么也可以 为同伴对象提供一个显式的名称,如下所示:
class Foo {
companion object Blah {
fun a() : Int = 1;
}
}
这将让您以同样的方式从Kotlin调用它,但是 来自java,如Foo.Blah.a()(这也可以在Kotlin中工作)。