Kotlin中的静态初始化块 [英] Static initialisation block in Kotlin

查看:151
本文介绍了Kotlin中的静态初始化块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

等效于静态初始化块科特林?

我了解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.

我的特定用例是,我想从Android AppCompat库和指令说要在Application类的静态初始化块中放入一些代码.

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.

推荐答案

从某些角度来看, companion object s 等效于Java类的静态部分.特别是,它们是在第一次使用类之前进行初始化的,这使您可以使用它们的init块代替Java静态初始化器:

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

这篇关于Kotlin中的静态初始化块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆