bsky
bsky

Reputation: 20242

Scala class fields not visible

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)

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: 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

I thought that getters and setters are created automatically for the fields. If that is true, why can't I access them?

Upvotes: 2

Views: 775

Answers (1)

Dima
Dima

Reputation: 40508

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.

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 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.

Upvotes: 6

Related Questions