我有一个像这样组织的代码:
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对象中?是否有更清洁(可能)更短的东西?
答案 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)
兼容。使其通用允许维护输入列表的元素类型。