Basic FunctionN cov/contravariance

68 views Asked by At

I have pretty much a code organized like this:

class Person(name: String, val addr: Int) {
  def distance(that: Person) = this.addr - that.addr
}

class Employee(_name: String, role: String, _addr: Int) extends Person(_name, _addr) {
  def smgth = 1
}


val anna = new Employee("Anna", "Secretary", 1)
val boss = new Employee("Boss", "Boss", 2)


def filterP(l: List[Person]) = l filter { (x) => x.addr > 1 }
def fltrdEmployees(l: List[Employee]): List[Employee] = filterP(l)

which gives:

Error:(19, 65) type mismatch;
 found   : List[A$A126.this.Person]
 required: List[A$A126.this.Employee]
def fltrdEmployees(l: List[Employee]): List[Employee] = filterP(l);}
                                                           ^

I understand it is a probl with cov. I have seen cov-contra-variance being applied to classes in the classic Box[T] example.

I am also somehow aware of the FunctionN object

How to fix this? Do I need to wrap the stuff in an adhoc object that exposes my desired method? Is there something cleaner (and possibly) shorter?

1

There are 1 answers

0
Lee On BEST ANSWER

You can fix it by making filterP generic:

def filterP[T <: Person](l: List[T]) = l filter { (x) => x.addr > 1 }

The covariance of List is what allows you to supply a List[Employee] where a List[Person] is required, however the problem is that a List[Person] is being returned which is not compatible with List[Employee]. Making it generic allows the element type of the input list to be maintained.