Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing generic case classes in Scala
    text
    copied!<p>I wonder whether using generics for Scala case classes can save some boilerplate code.</p> <p>Let's save I have the following class hieararchy to emulate a "variant" type that boxes a set of types and allows unboxing them using pattern matching:</p> <pre><code>sealed abstract class Box; case class DoubleBox(v: Double) extends Box; case class StringBox(v: String) extends Box; case class BooleanBox(v: Boolean) extends Box; def typeName(b: Box) = b match { case DoubleBox(v) =&gt; "Double" case StringBox(v) =&gt; "String" case BooleanBox(v) =&gt; "Boolean" case _ =&gt; "Unknown" } </code></pre> <p>There may be places in the code where it would be more convenient to deal with the leaf case classes if they were generics. Something like:</p> <pre><code>sealed abstract class Box; case class TypedBox[T](v: T) extends Box; def typeName2(b: Box) = b match { case TypedBox[Double](v) =&gt; "Double" case TypedBox[String](v) =&gt; "String" case TypedBox[Boolean](v) =&gt; "Boolean" case _ =&gt; "Unknown" } </code></pre> <p>But this doesn't compile. As far as I understand this syntax is not really recognized as valid Scala syntax.</p> <p>Is it possible to make what I want working or it's a bad idea and I just don't get something?</p> <p><strong>EDIT:</strong> Vinicius answered my question, but looking at the answer I have another question. Is it possible to hint the compiler somehow that only certain list of types can be used to parameters TypedBox? I want that to make sure the compiler can still do exhaustiveness check of TypedBox usage/matching.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload