基本功能N cov / contravariance

时间:2015-06-24 13:06:24

标签: scala covariance 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);}
                                                           ^

我知道它是probl with cov。我在经典Box[T]示例中看到了cov-contra-variance being applied to classes

我也知道FunctionN object

如何解决这个问题?我是否需要将这些内容包装在一个公开我想要的方法的adhoc对象中?是否有更清洁(可能)更短的东西?

1 个答案:

答案 0 :(得分:2)

您可以通过filterP通用:

来解决此问题
def filterP[T <: Person](l: List[T]) = l filter { (x) => x.addr > 1 }

List的协方差允许您提供List[Employee],其中List[Person]是必需的,但问题是返回List[Person]而不是List[Employee]select device_id, module from configs where values not in (select values from configs where device_id = 1) 兼容。使其通用允许维护输入列表的元素类型。