Home > Software design >  Calling method without creating an instance
Calling method without creating an instance

Time:10-15

I want to call a function in the 'static' way i heard there isn't an equivalent for static in Kotlin so I'm looking into a way to make it work.

fun main() {
var ob1 : Ob1 = Ob1()
ob1.try1()
}

class Ob1{
        fun try1() = println("try 1S")
}

If I use java i would just name it static than call the function directly.

Thanks on advance..

CodePudding user response:

You can define function outside class or simply define it in a companion object:

class Ob1{
    companion object{
        fun try1() = println("try 1S")
    }
}

fun main() {
    Ob1.try1()
}

Yo can read more in official documentation

  • Related