Static initialisation block in Kotlin

后端 未结 2 1330
谎友^
谎友^ 2021-02-03 16:39

What is the equivalent of a static initialisation block in Kotlin?

I understand that Kotlin is designed to not have static things. I am looking for something with equiva

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-03 17:19

    From some point of view, companion objects in Kotlin are equivalent to static parts of Java classes. Particularly, they are initialized before class' first usage, and this lets you use their init blocks as a replacement for Java static initializers:

    class C {
        companion object {
            init {
                //here goes static initializer code
            }
        }
    }
    

提交回复
热议问题