我想澄清scala中的一些概念
class Test(a:Int) {
def print = println(a)
}
class Test1(val a:Int) {
def print = println(a)
}
class Test2(private val a:Int) {
def print = println(a)
}
val test = new Test(1)
val test1 = new Test1(1)
val test2 = new Test2(1)
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试访问in test,test1,test2时.
Scala打印
scala> test.a
<console>:11: error: value a is not a member of Test
scala> test1.a
res5: Int = 1
scala> test2.a
<console>:10: error: value a cannot be accessed in Test2
Run Code Online (Sandbox Code Playgroud)
我理解Integer a是Test1和Test2的一个字段.但是Integer a和Class Test的关系是什么?显然,整数a不是Test类的字段,但它可以在print函数中访问.
查看正在发生的事情的最佳方法是对生成的Java类进行反编译.他们来了:
public class Test
{
private final int a;
public void print()
{
Predef..MODULE$.println(BoxesRunTime.boxToInteger(this.a));
}
public Test(int a)
{
}
}
public class Test1
{
private final int a;
public int a()
{
return this.a; }
public void print() { Predef..MODULE$.println(BoxesRunTime.boxToInteger(a())); }
public Test1(int a)
{
}
}
public class Test2
{
private final int a;
private int a()
{
return this.a; }
public void print() { Predef..MODULE$.println(BoxesRunTime.boxToInteger(a())); }
public Test2(int a)
{
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,在每种情况下都a成为private final int成员变量.唯一的区别在于生成了哪种访问器.在第一种情况下,不生成访问者,在第二种情况下生成公共访问者,在第三种情况下,它是私有的.