In Scala: I would like to define a type Message[T] (it needs to have this signature), which can be a message holding some data of type T, or an implicit message. I have
trait Message[T]
case object ImplicitMessage extends Message <- obviously doesn't compile
case class DataMessage[T](d: T) extends Message[T]
How should I define ImplicitMessage? I could make it a case class, but that is obviously not that nice, as it only want one instance of it.
UPDATE: I know I could simply remove [T] from Message, but I can't (requirement).
You could use Nothing
as in:
case object ImplicitMessage extends Message[Nothing]
Nothing
is a special type which is a subtype of all possible types and has no instances.
If you experience variance problems because of Message[T]
you can use the following trick:
object ImplicitMessage extends Message[Nothing] {
def apply[T]: Message[T] = this.asInstanceOf[Message[T]]
}
scala> ImplicitMessage[String]
res1: Message[String] = ImplicitMessage$@4ddf95b5
scala> ImplicitMessage[Long]
res2: Message[Long] = ImplicitMessage$@4ddf95b5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With