What is the equivalent of Java static methods in Kotlin?

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

    In Java, we can write in below way

    class MyClass {
      public static int myMethod() { 
      return 1;
      }
    }
    

    In Kotlin, we can write in below way

    class MyClass {
      companion object {
         fun myMethod() : Int = 1
      }
    }
    

    a companion is used as static in Kotlin.

    0 讨论(0)
  • 2020-11-27 10:03

    Kotlin has no any static keyword. You used that for java

     class AppHelper {
            public static int getAge() {
                return 30;
            }
        }
    

    and For Kotlin

    class AppHelper {
            companion object {
                fun getAge() : Int = 30
            }
        }
    

    Call for Java

    AppHelper.getAge();
    

    Call for Kotlin

    AppHelper.Companion.getAge();
    

    I think its working perfectly.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-27 10:04

    All static member and function should be inside companion block

      companion object {
        @JvmStatic
        fun main(args: Array<String>) {
        }
    
        fun staticMethod() {
        }
      }
    
    0 讨论(0)
提交回复
热议问题