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 equivalent semantics - code is run once when the class is first loaded.

My specific use case is that I want to enable the DayNight feature from Android AppCompat library and the instructions say to put some code in static initialisation block of Application class.

推荐答案

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

@voddan这并不是过分,实际上这是Kotlin网站上的建议:"当相应的类被加载(解析)时,一个伴随对象被初始化,匹配Java静态初始值设定项的语义."Semantic difference between object expressions and declarations

Kotlin相关问答推荐

在Kotlin中处理结果的高阶函数

Jetpack Compose Material3和Material2 Slider onValueChangeFinded()的行为不同

映射中列表类型的Kotlin可空接收器?

在Webflux应用程序中通过kotlin协程启动fire and forget job

处理合成层次 struct 中的深层按钮以切换视图

在协程上下文中重新抛出异常

如何在 Jetpack Compose 中启动和停止动画

Kotlin 如何使用其 get 函数在内部检索映射值

使用 StateFlow 时如何移除监听器?

多个不同的指针输入

PRDownloader 即使在实现库后也无法工作.未知参考:Android Studio 中的 PRDownloader

如何通过 compose 处理剪切区域?

为什么没有remember 的 mutableStateOf 有时会起作用?

这是什么 Kotlin 类型:(String..String?)

runBlocking 中的 deferred.await() 抛出的异常即使在被捕获后也被视为未处理

有没有办法在数据类构建时转换属性的值?

无法在Kotlin中使用argb color int值?

在 gradle android library kotlin 项目中禁用 META-INF/* 生成

Android Kotlin 创建类实现 Parcelable 在 writeToParcel 方法的 override中给出错误

Kotlin 中的填充字符串