简体   繁体   中英

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
}

As @Travis Brown has already stated, it looks like you're trying to express the variability of the return type (ie "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
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM