Function which generically takes a type and returns the same type

后端 未结 2 1568
心在旅途
心在旅途 2020-12-29 15:41

I am having a tough time understanding why the Scala compiler is unhappy about this function definition:

def trimNonWordCharacters[T <: Iterable[String]](         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 16:11

    [Entering as an answer rather than a comment because code in comments doesn't format properly]

    @Daniel, thanks for the explanation, I also found it useful. As Iterable derives from IterableLike, the following also seems to work, and is slightly more compact:

    import scala.collection.IterableLike
    import scala.collection.generic.CanBuildFrom
    def trimNonWordCharacters[T <: IterableLike[String, T]]
     (items: T)
     (implicit cbf: CanBuildFrom[T, String, T]): T =
     items map { _.replaceAll("\\W", "") }
    

提交回复
热议问题