[英]Scala trait as a method input - type mismatch error
I wrote a method that gets a trait type as an input. 我编写了一个将特征类型作为输入的方法。 This is the trait Localizable
: 这是Localizable
的特征:
import com.vividsolutions.jts.geom.Coordinate
trait Localizable {
val location : Coordinate
}
This is the method: 这是方法:
def localizeWithId(rdd : RDD[Localizable]) : RDD[(BigInt,Localizable)] = {
return rdd.map { case place =>
(getIdFromLocation(place.location.x, place.location.y), place)
}
}
The issue is that when I try to call this method, and send a case class that extends this trait as a parameter, I get an error of type mismatch. 问题是,当我尝试调用此方法并发送扩展此特征作为参数的case类时,出现类型不匹配的错误。
This is the case class: 这是案例类:
case class At (
eventDate : DateTime,
location : Coordinate
) extends Localizable
and this is the call: 这是电话:
val ats : RDD[At] = ...
val atsLocalized : RDD[(BigInt, At)] = localizeWithId(ats)
How can I solve it? 我该如何解决? Thanks. 谢谢。
Your problem is that here: 您的问题是在这里:
val atsLocalized : RDD[(BigInt, At)] = localizeWithId(ats)
you said you expect RDD[(BigInt, At)]
to be returned, while actual return type is declared as RDD[(BigInt,Localizable)]. 您说您希望返回RDD[(BigInt, At)]
,而实际的返回类型则声明为RDD [(BigInt,Localizable)]。
RDD
is invariant so you can't put RDD[B]
where RDD[A]
is expected even if B
would be subtype of A
. RDD
是不变的,所以你不能把RDD[B]
其中RDD[A]
即使预期B
将是亚型A
。 But that is not the case here anyway. 但这不是事实。
You can make your method generic like this: 您可以像这样使方法通用:
def localizeWithId[A <: Localizable](rdd: RDD[A]): RDD[(BigInt, A)]
requiring A
to be subtype of your trait. 要求A
是特征的子类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.