Scala class fields not visible

后端 未结 1 1221
悲&欢浪女
悲&欢浪女 2021-01-22 00:45

I have the following class, nested in an object called Solution:

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


        
相关标签:
1条回答
  • 2021-01-22 01:17

    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.

    0 讨论(0)
提交回复
热议问题