Yoav
Yoav

Reputation: 1039

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:

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.

Upvotes: 0

Views: 522

Answers (1)

Łukasz
Łukasz

Reputation: 8673

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.

Upvotes: 4

Related Questions