如果你真的想要一個「通用」的過濾功能,可以過濾呃,通過這些元素的任何屬性的基礎上,閉集的「允許」元素的任意值列表,而測繪成果到一些其他財產 - 這將是這個樣子:
def filter[T, P, R](
list: List[T], // input list of elements with type T (in our case: Employee)
propertyGetter: T => P, // function extracting value for comparison, in our case a function from Employee to String
values: List[P], // "allowed" values for the result of propertyGetter
resultMapper: T => R // function extracting result from each item, in our case from Employee to String
): List[R] = {
list
// first we filter only items for which the result of
// applying "propertyGetter" is one of the "allowed" values:
.filter(item => values.contains(propertyGetter(item)))
// then we map remaining values to the result using the "resultMapper"
.map(resultMapper)
}
// for example, we can use it to filter by name and return id:
filter(
List(emp1, emp2),
(emp: Employee) => emp.name, // function that takes an Employee and returns its name
List("abc"),
(emp: Employee) => emp.id // function that takes an Employee and returns its id
)
// List(1)
然而,這是一個非常簡單的斯卡拉操作周圍的一噸噪音:篩選和映射一個列表;這種特定用例可以寫成:
val goodNames = List("abc")
val input = List(emp1, emp2)
val result = input.filter(emp => goodNames.contains(emp.name)).map(_.id)
甚至:
val result = input.collect {
case Employee(id, name) if goodNames.contains(name) => id
}
Scala的內置map
,filter
,collect
功能是在這個意義上已經是「普通」,他們可以通過過濾/圖任何適用於集合中元素的函數。
嘗試過濾器功能。我不確定'比較'是什麼意思。這不僅僅是過濾器的標準嗎? – Tanjin