What is the equivalent of Java static methods in Kotlin?

前端 未结 28 1147
眼角桃花
眼角桃花 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条回答
  •  一向
    一向 (楼主)
    2020-11-27 10:03

    You can achieve the static functionality in Kotlin by Companion Objects

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

    Members of the companion object can be called by using simply the class name as the qualifier:

    Output:

    MyClass.staticField // This is an example of static field Object Decleration
    
    MyClass.getStaticFunction() : // This is an example of static function for Object Decleration
    

提交回复
热议问题