在Kotlin中没有静态关键字。

在Kotlin中表示静态Java方法的最佳方法是什么?


当前回答

让,你有一个班级学生。你有一个静态方法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

其他回答

Kotlin没有任何静态关键字。您可以在Java和Kotlin中使用下面的代码

 object AppHelper {
    @JvmStatic
    fun getAge() : Int = 30
}

Java类调用

AppHelper.getAge();

呼叫Kotlin类

AppHelper.getAge()

它非常适合我。谢谢

简单地使用这种方法

object Foo{
   fun foo() = println("Foo")
   val bar ="bar"  
}

Foo.INSTANCE.foo()

您可以通过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

将它们直接写入文件。

在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用于控制编译后的文件名,该文件名应该放在包名声明之前)。

您可以使用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()