Simon
Simon

Reputation: 6462

Scala: how to let the compiler infer the type from a function argument of type Seq[T]?

I'm making a generic function which sorts different subclasses of the following class:

class SortableByGeographicPoint(val geographicPoint: Int)

Its subclasses look like this one:

case class A(id: Int, override val geographicPoint: Int) extends SortableByGeographicPoint(geographicPoint)

My function is:

def sortByGeoPoint[T <: SortableByGeographicPoint](sequence: Seq[SortableByGeographicPoint]): Seq[T] = {
   sequence.sortBy(_.geographicPoint) map(_.asInstanceOf[T])
}

It is not so bad but I have to specify the type T when I want to use it, and I'm looking for a solution to avoid this.

I would like to do something like this:

def sortByGeoPoint(sequence: Seq[T <: SortableByGeographicPoint]): Seq[T] = {
   sequence.sortBy(_.geographicPoint) map(_.asInstanceOf[T])
}

Is it possible to do this, and how?

Upvotes: 1

Views: 94

Answers (3)

Ende Neu
Ende Neu

Reputation: 15783

Why don't you just use T in the Seq type parameter?

def sortByGeoPoint[T <: SortableByGeographicPoint](sequence: Seq[T]): Seq[T] =
  sequence.sortBy(_.geographicPoint)

Here T is a subtype of that class and you can access the geographicPoint parameter without problems.

Upvotes: 1

Alvaro Carrasco
Alvaro Carrasco

Reputation: 6172

No need for asInstanceOf, which is unsafe:

def sortByGeoPoint3[T <: SortableByGeographicPoint](sequence: Seq[T]): Seq[T] = 
  sequence.sortBy(_.geographicPoint)

Upvotes: 2

Simon
Simon

Reputation: 6462

Oops, I just have to do this:

  def sortByGeoPoint2[T <: SortableByGeographicPoint](sequence: Seq[SortableByGeographicPoint]): Seq[T] = {
      sequence.sortBy(_.geographicPoint) map(_.asInstanceOf[T])
  }

and I can call my function without giving the type like this:

sortByGeoPoint2(Seq(A(1, 2)))

Upvotes: 0

Related Questions