Home > OS >  Alternative way for kotlin static methods
Alternative way for kotlin static methods

Time:07-22

Im kinda new to Kotlin and I was wondering how I could make a static method. I have this code:

class Test() {
    
    var giorgor: String = "jiorgor"
    
    fun foo() = println(giorgor)
}

I want to access foo from somewhere else like this

fun main() {
    Test.foo() // WantedOutput: jiorgor
}

CodePudding user response:

If I'm understanding you correctly, you want an object instead of a class

object Test {
    var giorgor: String = "jiorgor"
    
    fun foo() = println(giorgor)
}

fun main() {
    Test.foo()
}

CodePudding user response:

The simplest way to do it without changing much is by making the class open or abstract and adding this

companion object Default: Test()

For some reason, if you make a companion object that implements its own class, every method can be used as a static one. If you wanted, you could also override an open method and make it have a different output for when it is used staticly:

fun main() {
    val test = Test()
    test.foo() //Output: "jiorgor"
    Test.foo() //Output: "static jiorgor"
}

public open class Test() {
    
    var giorgor: String = "jiorgor"
    
    open fun foo() = println(giorgor)
    companion object Default : Test() {
        override fun foo() = println("static jiorgor")
    }
}
  • Related