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

compile time error : reassignment to val

i am a newbie to scala and so far i learned how to use primary constructor and case classes for initialization of data members. I am just wandering, if there is a way to initialize val data member inside this. Initialization of var data member works fine below :-

class Person(){
    var name : String = _ 
    def this(n : String) {
      this()
      this.name = n
    }
  }
3
  • case class Person(name: String) or similarly with class params. Commented Jul 27, 2015 at 19:37
  • @som-snytt: Thanks for your quick response. case class or class param, i already learned from different resources on internet. just wandering, weather it is possible this way or not.. Commented Jul 27, 2015 at 19:41
  • You can never reassign a val. That's why val exists. It's the only difference between val and var. Commented Jul 27, 2015 at 19:44

1 Answer 1

8

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

In general, you just define all variables in the primary constructor itself as "class parameters": class Person(val name: String) if you need to receive the name for initialization or class Person() { val name = 'Joe' } if it is fixed.

This can be quite surprising coming from Java, as you are used to have constructors that produce the values and build the object directly. For such a case, the best solution is to use apply methods on a companion object:

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

That allows you to call Person(db, 3) to get a new person with custom initialization, but the constructor itself still receives all it needs to construct a new instance where all values are only assigned once.

Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps add that Scala classes have "class parameters" that constitute the "primary constructor".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.