基本函数N cov/contravariance

Basic FunctionN cov/contravariance

我的代码基本上是这样组织的:

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)

给出:

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);}
                                                           ^

我理解这是经典 Box[T] 示例中的 probl with cov. I have seen cov-contra-variance being applied to classes

我也不知何故知道 FunctionN object

如何解决这个问题?我是否需要将这些东西包装在一个公开我想要的方法的临时对象中?有没有更干净(并且可能)更短的东西?

您可以通过使 filterP 通用来修复它:

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

List 的协方差允许您在需要 List[Person] 的地方提供 List[Employee],但问题是返回 List[Person]List[Employee] 不兼容。使其成为通用的可以保持输入列表的元素类型。