我目前正在本节中介绍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
答案 0 :(得分:2)
您只初始化一次Base
。
因此,您也只能初始化一次size
。
因此,您将只执行一次also
块。
或者,以另一种方式回答您的问题,它不会第二次打印Initializing size in Base
,因为它不会第二次执行name.length.also { println("Initializing size in Base: $it") }
。