What is the equivalent of Java static methods in Kotlin?

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

    The exact conversion of the java static method to kotlin equivalent would be like this. e.g. Here the util class has one static method which would be equivalent in both java and kotlin. The use of @JvmStatic is important.

    Java code:

        class Util{
             public static String capitalize(String text){
             return text.toUpperCase();}
           }
    

    Kotlin code:

        class Util {
            companion object {
                @JvmStatic
                fun capitalize(text:String): String {
                    return text.toUpperCase()
                }
            }
        }
    

提交回复
热议问题