我有一個艱難的時間理解爲什麼Scala編譯器是不滿這個函數的定義:功能這一般需要一個類型並返回相同類型
def trimNonWordCharacters[T <: Iterable[String]](items: T): T =
items map { _.replaceAll("\\W", "") }
這裏是REPL輸出:
scala> def trimNonWordCharacters[T <: Iterable[String]](items: T): T =
items map { _.replaceAll("\\W", "") }
<console>:5: error: type mismatch;
found : Iterable[java.lang.String]
required: T
def trimNonWordCharacters[T <: Iterable[String]](items: T): T = items map { _.replaceAll("\\W", "") }
目標是傳遞Iterable的任何實現並獲得相同類型的返回。這可能嗎?
http://stackoverflow.com/questions/8235462/returning-original-collection-type-in-generic的重複方法 – 2012-04-04 22:24:34
@LuigiPlinge這個問題不需要'CanBuildFrom',因爲'filter'不需要它。這個問題是非常相似的,這個問題的_title_肯定涵蓋了它,但是在這裏需要更多一點才能使它工作。 – 2012-04-05 12:32:37