2015-06-24 65 views
0

我已經非常舉辦這樣的代碼:基本功能N COV /逆變

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對象中?有更清潔(可能)更短嗎?

回答

2

您可以通過filterP通用解決它:

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

List的協方差是什麼讓你提供在需要List[Person]一個List[Employee],但問題是,List[Person]被返回是與List[Employee]不兼容。使其具有通用性,可以維護輸入列表的元素類型。