gpt4 book ai didi

constructor - 是否保证构造函数内的调用顺序

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

假设我有一个带有主要构造函数的Kotlin(数据)类和一个辅助构造函数,该类通过调用一些方法来填充主要构造函数的val / var。我的问题是这些方法的调用顺序是否得到保证,即,在我的示例中checkConsitency是否会始终在extractNames之前调用

data class LawAndOrder(val sherifs: Int, val names: List<String>) {
constructor(westerners: List<Westerner>) :
this(sherifs = westerners.checkConsistency(),
names = westerners.extractNames())
}

data class Westerner(val name: String) {
val isCriminal: Boolean
get() = name == "Jesse James"
}

private fun List<Westerner>.checkConsistency(): Int {
println("Checking consistency")
if (isEmpty()) throw IllegalArgumentException("Crime and chaos")
if (any { it.isCriminal }) throw IllegalArgumentException("Inadmissible")
return size
}

private fun List<Westerner>.extractNames(): List<String> {
println("Extracting names")
return map { it.name }
}

fun main(args: Array<String>) {
val westerners = listOf(Westerner("John Wayne"), Westerner("Limonádový Joe"))
val lawAndOrder = LawAndOrder(westerners)
println(lawAndOrder)
}

最佳答案

Kotlin Language Specification对此有个说法(强调我的意思):

16.39. Order of Evaluation Generally, the order of evaluation is left to right, non-lazy (eager). Some expressions have special rules for order of evaluation of their constituent parts (some of them may be not evaluated at all). Order of evaluation of named arguments corresponds to their order at the invocation site, not the declaration site.

TODO

关于constructor - 是否保证构造函数内的调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239765/

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