Search code examples
androidkotlinstaticcompanion-objectkotlin-lateinit

Kotlin: are companion object lateinit vars initialised once?


Given the code below:

class Foo {
    companion object {
        lateinit var names: Array<String>
    }
    init {
        names = arrayOf("George", "Keith", "Martha", "Margret")
    }

}

If I created two instances of Foo:

var foo1 = Foo();
var foo2 = Foo();

is names going to be initialised/assigned twice, and therefore with any subsequent Foo initialisation?

My intent is to have a simple static variable names holding those predefined names.

Update:

This is assuming I do not want to have: var names: arrayOf("George", "Keith", "Martha", "Margret") inside companion object.


Solution

  • is names going to be initialised/assigned twice, and therefore with any subsequent Foo initialisation?

    As in init block its initializing names every time so it will create new Array for every instance.

    You can verify this with simple print

    class Foo {
        companion object {
            lateinit var names: Array<String>
        }
        init {
            println("Creating Foo")
            names = arrayOf("George", "Keith", "Martha", "Margret")
        }
    
        fun getHashCode():Int{
            return names.hashCode()
        }
    
    }
    
    fun main() {
    
        var foo1 = Foo();
        println(foo1.getHashCode());
        var foo2 = Foo();
        println(foo2.getHashCode());
    }
    

    In Output HashCode are different :

    Creating Foo
    746292446
    Creating Foo
    1072591677