Search code examples
scalatraitsgeneric-variance

How to write a method that takes a parameter with a covariant or contravariant bound in scala?


I am writing a scala program, which at some point should provide some status update for some task, and it could provide it also for groups of tasks. The point is that in different phases, the details are different. So there are in fact various implementations for the Details trait, which I did not include here.

case class GroupMessage [+S <: Details]
(
  id: String,
  statuses: List[StatusMessage[S]]
) 

case class StatusMessage [+S <: Details]
(
  id: String,
  phase: Phase,
  statusDetails: S
)

sealed trait Details {
  def getDetails: List[String]
}

Now, the problem is the method that receives this status updates, and I cannot get its signature right. If I just put def receiveStatus(status: StatusMessage) the compiler complains that StatusMessage takes type parameters. I thought I need something like def receiveStatus[S :> Details](status: StatusMessage[S]) but this does not compile either.


Solution

  • The symbol :> doesn't exist - you probably meant to use >:.

    But that still wouldn't compile, because you want S to be a subtype of Details (e.g. SpecialDetails, not a supertype (e.g. Any).

    def receiveStatus[S <: Details](status: StatusMessage[S])