gpt4 book ai didi

kotlin - 为什么要将val或var放在kotlin类构造函数中

转载 作者:行者123 更新时间:2023-12-04 09:23:16 26 4
gpt4 key购买 nike

只是学习Kotlin在下面的第一个代码中,其他代码中没有val关键字,
如果省略valvar,在这里有什么不同?

class Person(val firstName: String, val lastName: String) {
}

class Person(firstName: String, lastName: String) {
}

最佳答案

如果在构造函数中省略valvar,则唯一可访问这些参数的位置是在构造时评估的初始化语句。参见https://kotlinlang.org/docs/reference/classes.html

当您想在存储前用值做某事时,这很有用。在Java中,您可以将该代码放入构造函数主体中

class Person(firstName: String, lastName: String) {
// directly in val / var declarations
val firstName = firstName.capitalize()
val lastName = lastName

// in init blocks
val fullName: String
init {
fullName = "$firstName $lastName"
}

// secondary constructors can only see their own parameters
// and nothing else can access those
constructor(fullName: String) : this("", fullName)
}

但它也适用于 delegation using by
interface Named {
fun getName(): String
}
class Human(private val fname: String, private val lname: String) : Named {
override fun getName() = "$fname + $lname" // functions need val since
// value is resolved after construction
}
class Person2(firstName: String, lastName: String) : Named by Human(firstName, lastName)

class Person3(human: Human) : Named by human {
constructor(firstName: String, lastName: String): this(Human(firstName, lastName))
}

或在属性(property)委派中
class Person4(firstName: String, lastName: String) {
val fullName: String by lazy { "$firstName $lastName" }
}

注意:闭包是在初始化时捕获的,因此,当 lazy最终求值时,这些值仍然可用。

关于kotlin - 为什么要将val或var放在kotlin类构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52567108/

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