Abstract val instead of the argument of the main constructor

Consider these two classes and the way to instantiate:

class Person1(val name: String) val p1 = new Person1("John"); 

and

 abstract class Person2 { val name: String } val p2 = new Person2 { val name = "John" } 

Why do you prefer the latest version ( Person2 )? Each such declaration leads to the creation of a new subclass, and the code is a bit more verbose and less readable, however, the second idiom is used several times during programming in the Scala book. What are the advantages over direct field?

+8
scala scala-primary-constructor
source share
1 answer

One simple use case is with traits that cannot have constructor arguments.

+9
source share

All Articles