Reassigning to val on initialization in main constructor

class Person(){
    val name : String 
    def this(n : String) {
      this()
      this.name = n
    }
  }

      


compile time error : reassignment to val

      

I am new to scala and so far I have learned how to use primary constructor and case classes to initialize data members. I'm just wandering if there is a way to initialize the val data item inside this . Initializing var item works fine: -

class Person(){
    var name : String = _ 
    def this(n : String) {
      this()
      this.name = n
    }
  }

      

+3


source to share


1 answer


You just can't assign val after initialization. In Scala, the body of the IS class is a constructor, you can see examples here .

In general, you just define all the variables in the main constructor as "class parameters": class Person(val name: String)

if you need to get a name for initialization, or class Person() { val name = 'Joe' }

if it's fixed.

This can be quite unexpected from Java, since you are used to having constructors that produce values ​​and create an object directly. In such a case, the best solution is to use the application methods at the accompanying object:



    class Person(val name: String)
    object Person() {
        def apply(db: SomeDBConnectionWrapper, id: Int) = new Person(db.fetchName(id))
    }

      

This allows you to call Person(db, 3)

to get a new person with custom initialization, but the constructor itself still gets everything it needs to create a new instance where all the values ​​are assigned only once.

+3


source







All Articles