gpt4 book ai didi

kotlin - 派生类初始化顺序

转载 作者:行者123 更新时间:2023-12-02 13:22:30 25 4
gpt4 key购买 nike

目前,我正在本节的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com