What is the equivalent of Java static methods in Kotlin?

前端 未结 28 1210
眼角桃花
眼角桃花 2020-11-27 09:03

There is no static keyword in Kotlin.

What is the best way to represent a static Java method in Kotlin?

28条回答
  •  旧时难觅i
    2020-11-27 09:40

    Let, you have a class Student. And you have one static method getUniversityName() & one static field called totalStudent.

    You should declare companion object block inside your class.

    companion object {
     // define static method & field here.
    }
    

    Then your class looks like

        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
        }
    }
    

    Then you can use those static method and fields like this way.

    println("University : " + Student.getUniversityName() + ", Total Student: " + Student.totalStudent)
        // Output:
        // University : MBSTU, Total Student: 30
    

提交回复
热议问题