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?
You can fix it by making
filterP
generic:The covariance of
List
is what allows you to supply aList[Employee]
where aList[Person]
is required, however the problem is that aList[Person]
is being returned which is not compatible withList[Employee]
. Making it generic allows the element type of the input list to be maintained.