In Scala, how do you define a local parameter in the primary constructor of a class?

后端 未结 4 2057
走了就别回头了
走了就别回头了 2020-12-16 22:32

In Scala, how does one define a local parameter in the primary constructor of a class that is not a data member and that, for example, serves only to initialize a data membe

4条回答
  •  心在旅途
    2020-12-16 22:44

    After some experimentation, I determined that simply leaving out var or val in front of the parameter b will make it a local parameter and not a data member:

    class A(var a: Int)
    class B(b: Int) extends A(b)
    

    Java expansion:

    $ javap -private B
    Compiled from "construct.scala"
    public class B extends A implements scala.ScalaObject{
        public B(int);
    }
    
    $ javap -private A
    Compiled from "construct.scala"
    public class A extends java.lang.Object implements scala.ScalaObject{
        private int a;
        public A(int);
        public void a_$eq(int);
        public int a();
        public int $tag()       throws java.rmi.RemoteException;
    }
    

    Notice that class A has a private data member a due to the var a: Int in its primary constructor. Class B, however, has no data members, but its primary constructor still has a single integer parameter.

提交回复
热议问题