Jay*_*lor 6 generics collections type-theory functional-programming scala
我很难理解为什么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的任何实现并获得相同类型的退出.这可能吗?
Dan*_*ral 14
在map对方法Iterable返回的Iterable,所以即使T是的一个子类Iterable,它的map方法将返回Iterable.
为了更好地打字,你必须这样写:
import scala.collection.IterableLike
def trimNonWordCharacters[T <: Iterable[String]](items: T with IterableLike[String, T]): T =
     items map { _.replaceAll("\\W", "") }
但是,这也不会起作用,因为没有信息可以让地图T生成另一个地图T.例如,将a映射BitSet到a String不能导致a BitSet.因此,我们需要别的东西:东西,教你如何建立一个T从T,那里的映射元素类型String.像这样:
import scala.collection.IterableLike
import scala.collection.generic.CanBuildFrom
def trimNonWordCharacters[T <: Iterable[String]]
                         (items: T with IterableLike[String, T])
                         (implicit cbf: CanBuildFrom[T, String, T]): T =
     items map { _.replaceAll("\\W", "") }