What is the equivalent of Java static methods in Kotlin?

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

    There are 2 ways you can apply static in Kotlin

    First make a companion object under class

    For ex:

    class Test{
        companion object{
              fun isCheck(a:Int):Boolean{
                 if(a==0) true else false
              }
         }
    }
    

    you can call this function as

    Test.Companion.isCheck(2)
    

    Another way we can use is to make an object class

    object Test{
           fun isCheck(a:Int):Boolean{
                if(a==0) true else false
           }
    }
    

    Happy Coding!

提交回复
热议问题