kotlin - 派生类初始化顺序

标签 kotlin

目前,我正在本节的Kotlin文档中介绍Derived class initialization order

对于以下代码段...

open class Base(val name: String) {

  init { println("Initializing Base") }

  open val size: Int = name.length.also { println("Initializing size in Base: $it") }
}

class Derived(
    name: String,
    val lastName: String
  ) : Base(name.capitalize().also { println("Argument for Base: $it") }) {

  init { println("Initializing Derived") }

  override val size: Int =
    (super.size + lastName.length).also { println("Initializing size in Derived: $it") }
}

fun main(args: Array<String>) {
  println("Constructing Derived(\"hello\", \"world\")")
  val d = Derived("hello", "world")
}

执行时将输出以下内容:
Constructing Derived("hello", "world") Argument for Base: Hello Initializing Base Initializing size in Base: 5 Initializing Derived Initializing size in Derived: 10
我的问题是,为什么当override val size: Int = (super.size + lastName.length).also { println("Initializing size in Derived: $it") }被执行,它不会再次打印Initializing size in Base: 5吗?

我本以为它会打印如下内容:
Constructing Derived("hello", "world") Argument for Base: Hello Initializing Base Initializing size in Base: 5 Initializing Derived Initializing size in Base: 5 // Print because .also is called again ? Initializing size in Derived: 10

最佳答案

您只初始化一次Base
因此,您也只初始化一次size
因此,您将只执行一次also块。

或者,以另一种方式回答您的问题,它不会第二次打印Initializing size in Base,因为它不会第二次执行name.length.also { println("Initializing size in Base: $it") }

关于kotlin - 派生类初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52373783/

相关文章:

kotlin - 如何将 tailwindcss 添加到 KotlinJS

android - 使用 OkHttp 客户端执行原始 graphQL 查询

android - android滚动时图像在recylerview中被替换了吗?

java - Kotlin-android : unresolved reference databinding

android - 您如何使用 Room 和带有 LiveData 的 ViewModel 检索树结构,以便在包含子 RecyclerView 的 RecyclerView 中使用?

android - 是否可以在不依赖 kotlin-stdlib 的情况下在 JVM 或 Android 上使用 kotlin?

android - 在上传到 android 中的服务器之前在预览中显示图像

unit-testing - 如何为 MockWebServer 设置默认响应?

混淆后的Android类规范名称唯一性

android - 在 Firebase 中更新目标