加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 通常采用类型并返回相同类型的函数

发布时间:2020-12-16 09:28:35 所属栏目:安全 来源:网络整理
导读:我很难理解为什么Scala编译器对这个函数定义不满意: def trimNonWordCharacters[T : Iterable[String]](items: T): T = items map { _.replaceAll("W","") } 这是REPL输出: scala def trimNonWordCharacters[T : Iterable[String]](items: T): T = items
我很难理解为什么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的任何实现并获得相同类型的退出.这可能吗?

解决方法

Iterable上的map方法返回一个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.例如,将BitSet映射到String不能产生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,"") }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读