I just wanted to know if it is possible to iterate over a sealed trait in Scala? If not, why is it not possible? Since the trait is sealed it should be possible no?
What I want to do is something like that:
sealed trait ResizedImageKey {
/**
* Get the dimensions to use on the resized image associated with this key
*/
def getDimension(originalDimension: Dimension): Dimension
}
case class Dimension(width: Int, height: Int)
case object Large extends ResizedImageKey {
def getDimension(originalDimension: Dimension) = Dimension(1000,1000)
}
case object Medium extends ResizedImageKey{
def getDimension(originalDimension: Dimension) = Dimension(500,500)
}
case object Small extends ResizedImageKey{
def getDimension(originalDimension: Dimension) = Dimension(100,100)
}
What I want can be done in Java by giving an implementation to the enum values. Is there an equivalent in Scala?
This is actually in my opinion an appropriate use case for 2.10 macros: you want access to information that you know the compiler has, but isn't exposing, and macros give you a (reasonably) easy way to peek inside. See my answer here for a related (but now slightly out-of-date) example, or just use something like this:
Now we can write the following:
And this is all perfectly safe—you'll get a compile-time error if you ask for values of a type that isn't sealed, has non-object children, etc.
See this answer in another thread. The Lloydmetas Enumeratum library provides java Enum like features in an easily available package with relatively little boilerplate.
Something that can also solve the problem is the possibility to add an implicit convertion to add methods to the enum, instead of iteraring over the sealed trait.
Take a look at @TravisBrown's question As of shapeless 2.1.0-SNAPSHOT the code posted in his question works and produces a
Set
of the enumerated ADT elements which can then be traversed. I will recap his solution here for ease of reference (fetchAll
is sort of mine :-))There's no capability for this natively. It wouldn't make sense in the more common case, where instead of case objects you had actual classes as subclass of your sealed trait. It looks like your case might be better handled by an enumeration
Alternatively, you could create an enumeration on your own, possibly placing it in the companion object for convenience
The above mentioned solution based on Scala Macros works great. However it does not cases like :
To allow this, one can use this code: