Jai Prabhu
Jai Prabhu

Reputation: 207

Comparisons between generic types in Scala

Consider the following segment of code -

  abstract class Vehicle {
    val name: String
  }
  case class Car(name: String) extends Vehicle
  case class Truck(name: String) extends Vehicle

  abstract class VehicleContainer[T <: Vehicle] {
    def compare(that: VehicleContainer[T]): Int
  }

  class CarContainer(wheels: Int) extends VehicleContainer[Car] {
    override def compare(that: CarContainer): Int = ???
  }

The intention here is to have a compare method on the VehicleContainer that can be defined for each specific instance of VehicleContainer. The compare method comparison clause needs to be unique for each instance, because it could be comparing using attributes specific to that instance and hence not defined in the abstract base class VehicleContainer.

The trouble is that this does not work in it's current form, i.e. the override for compare is illegal. What I am not able to understand is how to accomplish this - define a base class that indicates that the sub classes need to implement a compare method, where the method argument to that compare method is that sub class itself. Would appreciate a pointer to the right concept here if it's some straightforward generics concept that I am missing here.

Thanks!

Upvotes: 1

Views: 70

Answers (1)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22605

One way to solve your problem could be use of F-bounded polymophism. You would just need one additional type parameter:

abstract class Vehicle {
    val name: String
}

case class Car(name: String) extends Vehicle
case class Truck(name: String) extends Vehicle

abstract class VehicleContainer[T <: Vehicle, V <: VehicleContainer[T, V]] {
    def compare(that: V): Int
}

class CarContainer(wheels: Int) extends VehicleContainer[Car, CarContainer] {
    override def compare(that: CarContainer): Int = ???
}

Upvotes: 4

Related Questions