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

scala – 使用视图时匹配错误

发布时间:2020-12-16 19:11:02 所属栏目:安全 来源:网络整理
导读:List(1,2,3,4).sliding(2).map({ case List(a,b) = a b }).forall(identity) 编译并返回true(尽管警告说匹配并非详尽无遗). List(1,4).view .sliding(2).map({ case List(a: Int,b: Int) = a b }).forall(identity) 编译(只要我们包含a和b的类型注释)但抛出M
List(1,2,3,4).sliding(2).map({ case List(a,b) => a < b }).forall(identity)

编译并返回true(尽管警告说匹配并非详尽无遗).

List(1,4).view
   .sliding(2).map({ case List(a: Int,b: Int) => a < b }).forall(identity)

编译(只要我们包含a和b的类型注释)但抛出MatchError:

scala.MatchError: SeqViewC(...) (of class scala.collection.SeqViewLike$$anon$1)
        at $anonfun$1.apply(<console>:12)
        at $anonfun$1.apply(<console>:12)
        at scala.collection.Iterator$$anon$19.next(Iterator.scala:335)
        at scala.collection.Iterator$class.forall(Iterator.scala:663)
        at scala.collection.Iterator$$anon$19.forall(Iterator.scala:333)

为什么?

解决方法

有趣的是,列表提取器List.unapplySeq无法提取SeqViewLike对象,这就是为什么会出现匹配错误.但另一方面,Seq可以.你可以这样看:

scala> val seqView = List(1,2).view.sliding(2).next
seqView: scala.collection.SeqView[Int,List[Int]] = SeqViewC(...)

scala> val List(a,b,_*) = seqView

scala.MatchError: SeqViewC(...) 

scala> val Seq(a,_*) = seqView
a: Int = 1
b: Int = 2

所以修复你的第二行将是:

List(1,4).view.sliding(2).map({ case Seq(a,b) => a < b }).forall(identity)
// res: Boolean = true

所以问题是List(1,4).view返回一个SeqView.

请注意,滑动已经返回一个迭代器,因此List(1,4).sliding(2)是懒惰的.可能是没有必要的观点.

(编辑:李大同)

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

    推荐文章
      热点阅读