Understandingdefinitionanddesugaringof"Option"inScala3book
I'm starting a Scala role in a few weeks yet I haven't written any Scala before (yes, my future employers know this), although I've written a lot of C# and Haskell. Anyway I was skimming through the Scala 3 book, and found this example:
enum Option[+T]:
case Some(x: T)
case None
Which apparently dusugars into:
enum Option[+T]:
case Some(x: T) extends Option[T]
case None extends Option[Nothing]
My two questions are:
- How exactly does the mechanism of this desugaring work? In particular why does
Someby default extendOption[T]whereasNoneextendsOption[Nothing]? - This seems like a strange way to define
Option. I would define it like this:
enum Option[+T]:
case Some(x: T) extends Option[T]
case None extends Option[T]
Indeed with None extending Option[None] wouldn't this fail?
Option[string] x = None;
As Option[T] is covariant in T and None is not a subtype of string?
I'm missing something quite fundamental here I'm sure.
THE END
二维码