Search code examples
kotlinstatic-methods

Alternative way for kotlin static methods


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

Test.foo() //I want to do this from somewhere else in the program

open class Test() {
    
    private giorgor: String? = null
    
    fun foo(value:String) {
        giorgor = value
    }
}

I need to change the value of giorgor from somewhere else in the code and I thought I could use a static method to do that but I dont know how. Test also needs to be an open class


Solution

  • One way to do this is by making the class open or abstract and adding this

    companion object Default: Test()
    

    This makes it act like every method of Test() is inside the companion object Default. If you wanted, you could also override an open method and make it have a different output for when it is used statically:

    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")
        }
    }