What is the equivalent of Java static methods in Kotlin?

前端 未结 28 1209
眼角桃花
眼角桃花 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:45

    I would like to add something to above answers.

    Yes, you can define functions in source code files(outside class). But it is better if you define static functions inside class using Companion Object because you can add more static functions by leveraging the Kotlin Extensions.

    class MyClass {
        companion object { 
            //define static functions here
        } 
    }
    
    //Adding new static function
    fun MyClass.Companion.newStaticFunction() {
        // ...
    }
    

    And you can call above defined function as you will call any function inside Companion Object.

提交回复
热议问题