What is the equivalent of Java static methods in Kotlin?

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

    Simply you need to create a companion object and put the function in it

      class UtilClass {
            companion object {
      //        @JvmStatic
                fun repeatIt5Times(str: String): String = str.repeat(5)
            }
        }
    

    To invoke the method from a kotlin class:

    class KotlinClass{
      fun main(args : Array) { 
        UtilClass.repeatIt5Times("Hello")
      }
    }
    

    or Using import

    import Packagename.UtilClass.Companion.repeatIt5Times
    class KotlinClass{
      fun main(args : Array) { 
         repeatIt5Times("Hello")
      }
    }
    

    To invoke the method from a java class:

     class JavaClass{
        public static void main(String [] args){
           UtilClass.Companion.repeatIt5Times("Hello");
        }
     }
    

    or by adding @JvmStatic annotation to the method

    class JavaClass{
       public static void main(String [] args){
         UtilClass.repeatIt5Times("Hello")
       }
    }
    

    or both by adding @JvmStatic annotation to the method and making static import in java

    import static Packagename.UtilClass.repeatIt5Times
    class JavaClass{
       public static void main(String [] args){
         repeatIt5Times("Hello")
       }
    }
    

提交回复
热议问题