在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
在Kotlin中没有静态关键字。
在Kotlin中表示静态Java方法的最佳方法是什么?
当前回答
您可以使用Companion Objects - kotlinlang
它可以通过首先创建该接口来显示
interface I<T> {
}
然后我们必须在该接口内部创建一个函数:
fun SomeFunc(): T
然后,我们需要一节课:
class SomeClass {}
在该类中,我们需要一个伴生对象:
companion object : I<SomeClass> {}
在那个同伴对象中,我们需要旧的SomeFunc函数,但是我们需要重写它:
override fun SomeFunc(): SomeClass = SomeClass()
最后,在所有这些工作下面,我们需要一些东西来支持静态函数,我们需要一个变量:
var e:I<SomeClass> = SomeClass()
其他回答
Kotlin没有任何静态关键字。您可以在Java和Kotlin中使用下面的代码
object AppHelper {
@JvmStatic
fun getAge() : Int = 30
}
Java类调用
AppHelper.getAge();
呼叫Kotlin类
AppHelper.getAge()
它非常适合我。谢谢
在kotlin中没有静态关键字。如果你想遵循DRY, kotlin文档建议使用包级函数。 创建一个扩展名为.kt的文件,并将您的方法放在其中。
package p
fun m(){
//fun body
}
编译后m将会有一个public static final void的签名
and
import p.m
☺
让,你有一个班级学生。你有一个静态方法getUniversityName()和一个静态字段totalStudent。
你应该在你的类中声明同伴对象块。
companion object {
// define static method & field here.
}
然后你的类看起来像
class Student(var name: String, var city: String, var rollNumber: Double = 0.0) {
// use companion object structure
companion object {
// below method will work as static method
fun getUniversityName(): String = "MBSTU"
// below field will work as static field
var totalStudent = 30
}
}
然后你可以像这样使用那些静态方法和字段。
println("University : " + Student.getUniversityName() + ", Total Student: " + Student.totalStudent)
// Output:
// University : MBSTU, Total Student: 30
将它们直接写入文件。
在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用于控制编译后的文件名,该文件名应该放在包名声明之前)。
你把函数放在“同伴对象”中。
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中工作)。