Declare a case object literal as its parent type?

Viewed 49

I have a singleton Banana class and want to avoid postfixing .type to all it's usages, so I've defined it like so:

sealed trait Banana
case object Banana extends Banana

Now I can have clean method signatures like def peel(foo: String): Banana

One minor annoyance though - it's kind of hard for me to reference the case object Banana while wanting it to actually be the parent type. Observe:

scala> sealed trait Banana; case object Banana extends Banana
trait Banana
object Banana

scala> Banana
val res0: Banana.type = Banana

scala> val banana: Banana = Banana
val banana: Banana = Banana

Now in the above, res0 is of type Banana.type, which is not the type I'm looking for! banana on the other hand, is indeed the type I want. Is it possible to get a banana literal of the latter type without first assigning it to a value?

Obviously Banana.asInstanceOf[Banana] works, but skirts around the whole pesky "compile time safety" thing.

1 Answers

Realize that this works:

type Banana = Banana.type
object Banana {
  // ...
}

Much better to just not use your hack in the first place.

If you do use the hack, note that expr: Type is an expression (it is called a type ascription):

sealed trait Banana; case object Banana extends Banana
def f[T](x: T)(implicit eq: T =:= Banana): T = x
// f(Banana) // tries to call with T = Banana.type, fails
f(Banana: Banana) // calls f with the right T = Banana instead of T = Banana.type
Related