【问题标题】:Scala: Pattern matching in tuplesScala:元组中的模式匹配
【发布时间】:2014-08-27 15:47:06
【问题描述】:

我知道元组在 Scala 中是不可变的。因此,我使用模式匹配来更改我的元组。我有一个包含两个 3 元组元素的 2 元组,每个元素都是一个序列。我的问题是:“如果第一个元组的第一个元素是空序列,请发送一些默认值。” 我的代码如下所示:

val (fooTuple, barTuple) = 
{
// function that returns a 2-tuple with elements that are 3-tuples
((a, b, c), (d, e, f)) //Each of these is a sequence
} match {
case ((Seq(), x, y), z) => ((Seq("default"), x, y), z)
}

它抛出一个MatchError 打印((a, b, c), (d, e, f)) 的值 我做错了什么?

【问题讨论】:

    标签: scala pattern-matching tuples


    【解决方案1】:

    当你的第一个元素不为空的情况下它失败了,你可以通过处理其他情况来解决这个问题:

    val (fooTuple, barTuple) = 
    {
    // function that returns a 2-tuple with elements that are 3-tuples
    ((a, b, c), (d, e, f)) //Each of these is a sequence
    } match {
      case ((Seq(), x, y), z) => ((Seq("default"), x, y), z)
      case other => other
    }
    

    所有其他案件将由case other => other处理

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 2021-02-15
      • 2015-05-30
      • 1970-01-01
      • 2012-10-31
      • 2017-12-16
      • 2016-05-17
      相关资源
      最近更新 更多