Scala 类字段不可见 [英] Scala class fields not visible
问题描述
我有以下类,嵌套在名为 Solution
的对象中:
I have the following class, nested in an object called Solution
:
class TreeNode(l_son: TreeNode, r_son: TreeNode,
l_val: Int, r_val: Int, nr: Int)
此外,在对象 Solution
中,我尝试引用其字段:
Also, in the object Solution
I try to reference its fields:
def query(left: Int, right: Int, node: TreeNode): Int = {
var sum = 0;
if(left <= node.l_val && node.r_val <= right) {
sum = node.nr
}
然而,每次我引用它的一个字段时,我都会收到一个错误:
However, every time I reference one of its fields, I get an error:
Solution.scala:36: 错误:值 l_val 不是 Solution.TreeNode 的成员if(left <= node.l_val && node.r_val <= right) {^Solution.scala:36: 错误:值 r_val 不是 Solution.TreeNode 的成员if(left <= node.l_val && node.r_val <= right) {^Solution.scala:37: 错误:值 nr 不是 Solution.TreeNode 的成员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 是为字段自动创建的.如果这是真的,为什么我不能访问它们?
I thought that getters and setters are created automatically for the fields. If that is true, why can't I access them?
推荐答案
像 class TreeNode(l_son: TreeNode, r_son: TreeNode,l_val: Int, r_val: Int, nr: Int)
没有定义任何类成员,只是构造函数参数.你仍然可以在类体内使用它们,就像它们是成员一样(除了,你不能做 this.l_son
),因为整个体是在构造函数中定义的,所以它本质上是一个闭包.
A declaration like class TreeNode(l_son: TreeNode, r_son: TreeNode,
l_val: Int, r_val: Int, nr: Int)
does not define any class members, just constructor arguments. You can still use them inside the class body almost as if they were members (except, you can't do this.l_son
), because entire body is defined inside the constructor, so it's essentially a closure.
要将类成员定义为构造函数参数,您必须在构造函数参数列表中以 val
或 var
为前缀:class TreeNode(val l_son: TreeNode ...)
To define a class member as a constructor parameter, you have to prefix it with val
or var
in the constructor parameter list:
class TreeNode(val l_son: TreeNode ...)
Case 类的特殊之处在于它们会自动为每个构造函数参数创建一个(不可变的)成员,以及一堆其他使 case 类有用的自动成员.
Case classes are special in that they will create a (immutable) member for every constructor parameter automatically, along with a bunch of other automatic members that make case classes useful.
这篇关于Scala 类字段不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!