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?
One simple use case is with traits, which cannot have constructor arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With