0
votes

I wrote a method that gets a trait type as an input. This is the trait 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.

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.

1
your problem might be that you annotated expected type as RDD[(BigInt, At)] while actual return type is RDD[(BigInt,Localizable)] which is type mismatch, exacly what you get. Solution might be to define def localizeWithId[A <: Localizable](rdd: RDD[A]): RDD[(BigInt, A)] - Łukasz
Thanks! that's perfect - Yoav
ok, let me post this as an answer then - Łukasz

1 Answers

4
votes

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 is invariant so you can't put RDD[B] where RDD[A] is expected even if B would be subtype of 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.