【发布时间】:2012-04-04 21:29:32
【问题描述】:
我很难理解为什么 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 的任何实现并获得相同类型的回退。这可能吗?
【问题讨论】:
-
@LuigiPlinge 这个问题不需要
CanBuildFrom,因为filter不需要它。这个问题非常相似,并且该问题的 title 肯定涵盖了它,但是这里需要更多的东西才能使它起作用。
标签: scala generics collections functional-programming type-theory