I notice that classes in Kotlin can have more than one init block. If so, they are executed in sequence.

What is a good use case for having more than one?

推荐答案

请考虑以下代码片段.

class Foo() {
  val x = Bar.getValue()

  init {
    // check the validity of x and abort if invalid
  }

  val y = Cow.getValue(x)  // requires x to be valid

  init {
    // continue with initialization
  } 
}

由于主构造函数不能有任何代码,如果没有多个init块,上述情况就不可能发生.换句话说,拥有多个init块的能力有助于解决初始化期间涉及属性的依赖性;当属性为只读时,情况就更糟了.

Update on 10/16/2021: We can achieve the same behavior by moving the assignment of read-only (RO) properties into a single init block. However, by doing so, we will separate the declaration of a RO property and its initialization. In comparison, multiple init blocks help keep the declaration and initialization of RO properties together while allowing any dependent computation to follow the property initialization. Consequently, the code is a bit cleaner, easy to read/understand, and modular (as described by @mightyWOZ's reply).

Kotlin相关问答推荐

如何在操作系统版本上正确获取Room数据库的路径>;=26 sdk?

Kotlin-elvis算子don';不使用map.get()

为什么我的通用Kotlin函数中的这个转换未经判断?

如何判断给定字符串是否多次包含另一个子字符串?

为空数组添加值

如何使用 Hilt 注入应用程序:ViewModel 中的上下文?

在 kotlin 中模拟伴随对象函数

java - 如何将函数作为参数从java传递给kotlin方法?

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

Android:在 DAO 中使用 Room 数据库和 LiveData 架构

为什么 Kotlin Pair 中的条目不可变?

Kotlin中的下划线名称是为什么保留的?

Kotlin JVM 和 Kotlin Native 有什么区别?

将 Double 转换为 ByteArray 或 Array Kotlin

我应该使用Kotlin数据类作为JPA实体吗?

在Kotlin中将列表转换为对的惯用方法

在android java类中使用Kotlin扩展

Kotlin 中内部可见性修饰符的范围

使用 Moshi/Retrofit2 访问深度嵌套的 JSON 数组

从 java 活动 *.java 启动 kotlin 活动 *.kt?