Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

case object of generic trait

Tags:

scala

traits

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).

like image 414
user1377000 Avatar asked Mar 24 '13 14:03

user1377000


1 Answers

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
like image 192
paradigmatic Avatar answered Sep 20 '22 20:09

paradigmatic