gpt4 book ai didi

Scala 类字段不可见

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

我有以下类,嵌套在一个名为 Solution 的对象中:

class TreeNode(l_son: TreeNode, r_son: TreeNode,
l_val: Int, r_val: Int, nr: Int)

此外,在对象 Solution 中,我尝试引用它的字段:

def query(left: Int, right: Int, node: TreeNode): Int = {
var sum = 0;
if(left <= node.l_val && node.r_val <= right) {
sum = node.nr
}

但是,每次我引用它的一个字段时,我都会得到一个错误:

Solution.scala:36: error: value l_val is not a member of Solution.TreeNode if(left <= node.l_val && node.r_val <= right) { ^ Solution.scala:36: error: value r_val is not a member of Solution.TreeNode if(left <= node.l_val && node.r_val <= right) { ^ Solution.scala:37: error: value nr is not a member of Solution.TreeNode sum = node.nr

我认为 getter 和 setter 是为字段自动创建的。如果这是真的,为什么我不能访问它们?

最佳答案

class TreeNode(l_son: TreeNode, r_son: TreeNode,
l_val: Int, r_val: Int, nr: Int)
不定义任何类成员,只是构造函数参数。您仍然可以在类体内使用它们,就像它们是成员一样(除了,您不能执行 this.l_son),因为整个类体都是在构造函数中定义的,所以它本质上是一个闭包。

要将类成员定义为构造函数参数,您必须在构造函数参数列表中使用 valvar 作为前缀:class TreeNode(val l_son: TreeNode ...)

案例类的特殊之处在于它们会自动为每个构造函数参数创建一个(不可变的)成员,以及一堆使案例类有用的其他自动成员。

关于Scala 类字段不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34578854/

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