What is the equivalent of Java static methods in Kotlin?

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

    Use object to represent val/var/method to make static. You can use object instead of singleton class also. You can use companion if you wanted to make static inside of a class

    object Abc{
         fun sum(a: Int, b: Int): Int = a + b
        }
    

    If you need to call it from Java:

    int z = Abc.INSTANCE.sum(x,y);
    

    In Kotlin, ignore INSTANCE.

提交回复
热议问题