2013-02-08 71 views
0

我上網通過斯卡拉不耐煩特定的語法,但不幸的是它假定以前的Java經驗和這裏是如何[T]使用的理解:這是什麼叫斯卡拉

object Iterables { 
    def filter[T](unfiltered: Iterable[T], predicate: T => Boolean): Iterable[T] = {...} 
    def find[T](iterable: Iterable[T], predicate: T => Boolean): T = {...} 
} 

爲每個實例的語法[T]T這裏相當混亂。它在函數名稱後面直接列出時具有什麼意義,如filter[T]。我在參數列表中瞭解到,我們正在尋找類型爲T的Iterable。但是如果T是一種類型,predicate: T => Boolean是什麼意思?

回答

2

類型參數化方法

Scala中的一個方法可以接受一個或更多type parameter s,就像class,objecttrait一樣。

在這種情況下,這意味着可以調用類型爲T的相同方法,該類型可能因呼叫而異,但必須在定義內保持一致。

讓我們例如使用

def filter[T](unfiltered: Iterable[T], predicate: T => Boolean): Iterable[T] 

的方法希望你傳遞:
- 是一種把TBooleanpredicate
功能 - 的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) 

                      ^
5

此聲明:

def filter[T](unfiltered: Iterable[T], predicate: T => Boolean): Iterable[T] 

可以如下:對於任何類型的T此函數接受該類型,並從該類型Boolean函數的Iterable。最後它返回相同類型的Iterable

上面基本上鍵入意思是:你可以調用這個函數Iterable[String]Iterable[Date]Iterable[Foo] - 你的想法。但是,無論您選擇哪種類型,都必須在所有地方都一樣。因此,例如:

val result = filter(List("a", "bb", "ccc"), (s: String) => s.length() > 1) 

是正確的。但是,這並不:

val result: Seq[Int] = filter(List("a"), (s: String) => s.length() > 1) 
0

它被稱爲泛型方法

(一個類似的功能也用Java可用,C#,和C++(其中它被稱爲,模板函數))