Extending the scala class with less ceremony

I am probably doing something wrong. When I extend the class, I specify the mapping between the extension constructor and the extended class constructor:

class Base(one: String, two: String)
case class Extended(one: String, two: String, three: String) extends Base(one, two)

      

How can I instead use something like any of the following, which implies the default display?

class Base(one: String, two: String) 
case class Extended(one: String, two: String, three: String) extends Base

class Base(one: String, two: String) 
case class Extended(three: String) extends Base

      

I am probably missing a cleaner way to just add a parameter without this ceremony. Or should I be using trait, not subclasses, for such a simple thing ....

+3


source to share


1 answer


All parameters of the class case

generated by the class apply

must be specified in the class declaration case

, so your second suggestion may not work. The first can be done if Base

abstract, using abstract val

s:

abstract class Base {
  // no initializers!
  val one : String
  val two : String

  def print { println("Base(%s, %s)" format (one, two)) }
}
// Note: constructor arguments of case classes are vals!
case class Extended(one: String, two: String, three: String) extends Base
...
Extended("foo", "bar", "baz").print // prints 'Base(foo, bar)'

      



However, the names must match exactly.

+10


source







All Articles