類型參數化方法
Scala中的一個方法可以接受一個或更多type parameter
s,就像class
,object
或trait
一樣。
在這種情況下,這意味着可以調用類型爲T
的相同方法,該類型可能因呼叫而異,但必須在定義內保持一致。
讓我們例如使用
def filter[T](unfiltered: Iterable[T], predicate: T => Boolean): Iterable[T]
的方法希望你傳遞:
- 是一種把T
到Boolean
(predicate
)
功能 - 的T
S(unfiltered
)
的Iterable
結果將是T
的另一個Iterable
。
該方法將在unfiltered
對象上迭代,並且對於每個元素應用predicate
來確定是否必須對其進行過濾。
所得Iterable
只包含滿足predicate
(即那些t
爲誰predicate(t)
回報true
)
您可以撥打過濾器對於任何類型的T
,限制就是它必須是FO所有參數和一致的元素結果類型。
例子
//filtered is List(2,3)
val filtered: Iterable[Int] = filter(List(1, 2, 3), (i: Int) => i > 1)
//filtered is List("b", "abc")
val filtered: Iterable[String] = filter(List("a", "b", "abc"), (s: String) => s contains "b")
//filtered is List(Some(1), Some(2))
val filtered: Iterable[Option[Int]] = filter(List(Some(1), Some(2), None), (op: Option[Int]) => op.isDefined)
//you can't call this because T is not the same everywhere it's used
val filtered: Iterable[Int] = filter(List(1, 2, 3), (op: Option[Int]) => op.isDefined)
//this will get you
<console>:12: error: type mismatch;
found : Option[Int] => Boolean
required: Int => Boolean
val filtered: Iterable[Int] = filter(List(1, 2, 3), (op: Option[Int]) => op.isDefined)
^