Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract val instead of primary constructor argument

Consider these two classes and the way the instances are created:

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 would one prefer the latter (Person2) version? Every such a declaration causes new subclass to be created, also the code is slightly more verbose and less readable, however the second idiom is used throughout the Programming in Scala book several times. What are the advantages over straightforward field?

like image 226
Tomasz Nurkiewicz Avatar asked Jul 31 '11 14:07

Tomasz Nurkiewicz


1 Answers

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

like image 95
Jean-Philippe Pellet Avatar answered Sep 22 '22 02:09

Jean-Philippe Pellet