a sealed trait is the same as a sealed class ?
As far as sealed
goes, yes. They share the normal differences between trait
and class
, of course.
Or, if not, what are the differences ?
Moot.
When is it a good idea to use a sealed trait (and when not) ?
If you have a sealed class X
, then you have to check for X
as well as any subclasses. The same is not true of sealed abstract class X
or sealed trait X
. So you could do sealed abstract class X
, but that's way more verbose than just trait
and for little advantage.
The main advantage of using an abstract class
over a trait
is that it can receive parameters. That advantage is particularly relevant when using type classes. Let's say you want to build a sorted tree, for instance. You can write this:
sealed abstract class Tree[T : Ordering]
but you cannot do this:
sealed trait Tree[T : Ordering]
since context bounds (and view bounds) are implemented with implicit parameters. Given that traits can't receive parameters, you can't do that.
Personally, I prefer sealed trait
and use it unless some particular reason makes me use a sealed abstract class
. And I'm not talking about subtle reasons, but in-your-face reasons you cannot ignore, such as using type classes.