[英]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)".
它给出错误“必需的T,但找到了PostResult(或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. 正如@Travis Brown所说的,看起来您正在尝试通过泛型表达返回类型的可变性(即“它是
PostResult
还是PostError
”),而实际上您所需要的只是父代特征。
Assuming your SDFCResult
was an anonymization error where you meant to use ResultTrait
, I would use the following: 假设您的
SDFCResult
是一个匿名化错误,您打算使用ResultTrait
,我将使用以下内容:
// 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.