What is the equivalent of Java static methods in Kotlin?

前端 未结 28 1125
眼角桃花
眼角桃花 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 09:57

    A. Old Java Way :

    1. Declare a companion object to enclose a static method / variable

      class Foo{
      companion object {
          fun foo() = println("Foo")
          val bar ="bar"  
          }
      }
      
    2. Use :

      Foo.foo()        // Outputs Foo    
      println(Foo.bar) // Outputs bar
      


    B. New Kotlin way

    1. Declare directly on file without class on a .kt file.

      fun foo() = println("Foo")
      val bar ="bar"
      
    2. Use the methods/variables with their names. (After importing them)

      Use :

      foo()        // Outputs Foo          
      println(bar) // Outputs bar     
      

提交回复
热议问题