Search code examples
scalagenericsscala-generics

Scala generics in function return value


I have these classes defined.

trait ResultTrait {
}
case class PostResult (
  @Key("_id") id: String,
  success: String,
  errors: Seq[String] = Seq.empty
) extends ResultTrait

case class PostError (
  message: String,
  errorCode: String
) extends ResultTrait

This won't compile. It gives error "Required T, but found PostResult (or PostError)".

def postLead[T <: SFDCResult](accessToken: AccessToken):
        Future[T] = {
     // depends on response from request, return PostResult or PostError
}

Solution

  • As @Travis Brown has already stated, it looks like you're trying to express the variability of the return type (i.e. "it's either a PostResult or a PostError") through generics, when really all you need is the parent trait.

    Assuming your SDFCResult was an anonymization error where you meant to use ResultTrait, I would use the following:

    // Make the trait sealed so we can only have our two known implementations:
    sealed trait ResultTrait {}
    ...
    // Two subclasses as before
    

    And then your method should just be:

    def postLead(accessToken: AccessToken):Future[ResultTrait] = {
      // depends on response from request, return PostResult or PostError
    }