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

scala – 什么是模式匹配序列理解的惯用方式?

发布时间:2020-12-16 09:30:26 所属栏目:安全 来源:网络整理
导读:val x = for(i - 1 to 3) yield ix match { case 1 :: rest = ... // compile error} constructor cannot be instantiated to expected type; found : collection.immutable.::[B] required: scala.collection.immutable.IndexedSeq[Int] 这是与MatchError w
val x = for(i <- 1 to 3) yield i
x match {
    case 1 :: rest => ... // compile error
}

constructor cannot be instantiated to expected type; found :
collection.immutable.::[B] required:
scala.collection.immutable.IndexedSeq[Int]

这是与MatchError when match receives an IndexedSeq but not a LinearSeq相同的问题。

问题是,怎么做呢?添加到.toL??ist到处都不正确。并创建一个自己的提取器,处理每个Seq(如另一个问题的答案所述)会导致一个混乱,如果每个人都会这样做…

我猜问题是,为什么我不能影响什么是返回类型的序列推理,或者:为什么这样一个广义的Seq提取器是标准库的一部分?

解决方法

那么你可以模式匹配任何序列:

case Seq(a,b,rest @ _ *) =>

例如:

scala> def mtch(s: Seq[Int]) = s match { 
  |      case Seq(a,rest @ _ *) => println("Found " + a + " and " + b)
  |      case _ => println("Bah") 
  |    }
mtch: (s: Seq[Int])Unit

那么这将匹配任何具有多于(或等于)2个元素的序列

scala> mtch(List(1,2,3,4))
Found 1 and 2

scala> mtch(Seq(1,3))
Found 1 and 2

scala> mtch(Vector(1,2))
Found 1 and 2

scala> mtch(Vector(1))
Bah

(编辑:李大同)

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

    推荐文章
      热点阅读