加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala构造函数参数修饰符

发布时间:2020-12-16 18:11:47 所属栏目:安全 来源:网络整理
导读:我想澄清 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 Tes
我想澄清 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)

现在,当我尝试访问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

我理解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)
  {
  }
}

如您所见,在每种情况下,a成为私有的最终int成员变量.唯一的区别在于生成了哪种访问器.在第一种情况下,不生成访问者,在第二种情况下生成公共访问者,在第三种情况下,它是私有的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读