Is it possible to express recursive type definitions like the following in Scala?
type test = Either[List[test], Int]
UPDATE
My intention is to express a function like the following:
def flatten[T](list: List[Either[List[T], T]]): List[T] = list flatMap {
case Left(list) => list
case Right(element) => List(element)
}
but that accepts a similar structure of arbitrary depth
You cannot have a recursive type alias like that. But if you create a separate class, it’s no problem:
(Most interesting classes in programming are actually recursive.)
The reason why you cannot have a recursive
typealias like yours is that the compiler needs to expandtypealiases in order to tell if something has the type or not. But a recursive type alias likeexpands to infinity:
With classes, this doesn’t happen, because the class “wraps” recursive values into something with a well defined type (like
Test[T]in this example). The “expansion” of types only happens if you reference something that’s inside (valuein this case).