我有一个艰难的时间理解为什么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