How do you define a local var/val in the primary constructor in Scala?

后端 未结 4 797
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 15:20

In Scala, a class\'s primary constructor has no explicit body, but is defined implicitly from the class body. How, then, does one distinguish between fields and local values

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 16:04

    Another option we have is to make the primary object constructor private and use a companion object's apply method as a builder. If we apply (pun is not intended) this approach to your example it will look like this:

    class R private (val x: Int, val y: Int);
    
    object R {
      def apply(n: Int, d: Int): R = {
        val g = myfunc;
        new R(n / g, d / g);
      }
    }
    

    To create an R instance instead of:

    val r = new R(1, 2);
    

    write:

    val r = R(1, 2);
    

    This is a little bit verbose, but it could be worse, I think :). Let's hope that private[this] vals will be treated as temporary variables in future releases of Scala. Martin himself hinted that.

提交回复
热议问题