Sealed trait hierarchies and downcasting
Rüdiger Klaehn <[email protected]>
| Newsgroups | gmane.comp.lang.scala |
|---|---|
| Message-ID | <CAGA++nne1Lb+Cysv_fn2P4v2x=RVtF__0GyQYzuzZgYrpH=Jhw@mail.gmail.com> |
Hi all,
one pattern I like to use is the following:
sealed trait Foo
object Foo {
def empty: Foo = ...
def apply(...): Foo = ...
private sealed trait Tree extends Foo
private case class Leaf(...) extends Tree
private case class Branch(...) extends Tree
}
Basically have a sealed trait or sealed abstract class for the public
interface, and then a completely
private hierarchy that is the only implementation. This is a nice way
to hide implementation details while still not having the overhead of
boxing or the annoyance of wrapping in a value class.
However, a problem with this approach is that the compiler does not
seem to know that a Foo must always be a Tree. So this won't work:
def sumImpl(that: Tree) = ...
def +(that: Foo): Foo = sumImpl(that)
I have to write
def +(that: Foo): Foo = sumImpl(that.asInstanceOf[Tree])
Would it be possible to allow a downcast when it is guaranteed to succeed?
Cheers,
Rüdiger
--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/d/optout.