Random object of a common attribute

In Scala: I would like to define the type Message [T] (it must have this signature), which can be a message containing 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 to define ImplicitMessage? I could make this a case class, but this is obviously not so good as it only wants one instance of it.

UPDATE: I know that I can simply remove [T] from Message, but I cannot (requirement).

+4
source share
2 answers

You can use Nothing as in:

 case object ImplicitMessage extends Message[Nothing] 

Nothing is a special type that is a subtype of all possible types and has no instances.

If you have problems with deviations due to 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 
+3
source

You can define an implicit method with a type parameter as follows:

 implicit def message[T]: Message[T] = new Message[T] {} 

EDIT: If you are really only one instance (which you really do not need to do, because you are lying to the compiler, and it is very likely that you are doing it wrong), you can simply cast null:

 implicit def message[T]: Message[T] = null.asInstancOf[Message[T]] 
+1
source

All Articles