Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对scala中的对列表使用模式匹配时出现编译器错误_Scala_Compiler Errors_Pattern Matching - Fatal编程技术网

对scala中的对列表使用模式匹配时出现编译器错误

对scala中的对列表使用模式匹配时出现编译器错误,scala,compiler-errors,pattern-matching,Scala,Compiler Errors,Pattern Matching,我正在学习Scala模式匹配,遇到了以下问题: 假设我有整数列表,并使用模式匹配来匹配最后一个元素: val list = 1 :: 2 :: 3 :: Nil list match { case xs :+ 3 => println("Matched") case _ => println("Not matched") } 在这种情况下,它可以正常工作,并打印“匹配” 但当我使用配对列表时,问题就出现了: val list = ('a', 1) :: ('b',

我正在学习Scala模式匹配,遇到了以下问题:

假设我有整数列表,并使用模式匹配来匹配最后一个元素:

val list = 1 :: 2 :: 3 :: Nil

list match { 
   case xs :+ 3 => println("Matched")
   case _ => println("Not matched")
}
在这种情况下,它可以正常工作,并打印“匹配”

但当我使用配对列表时,问题就出现了:

val list = ('a', 1) :: ('b', 2) :: ('c', 3) :: Nil
list match {
   case xs :+ ('c', 3) => println("Matched")
   case _ => println("Not mathed")
}
当我写这篇文章时,我得到以下错误:

<console>:14: error: too many patterns for object :+ offering
(List[(Char, Int)], (Char, Int)): expected 2, found 3
          case xs :+ ('c', 3) => println("Matched")
                  ^
 <console>:14: error: type mismatch; 
 found   : Char('c')
 required: (Char, Int)
          case xs :+ ('c', 3) => println("Matched")
:14:错误:对象的模式太多
(列表[(字符,Int)],(字符,Int)):应为2,找到3
案例xs:+('c',3)=>println(“匹配”)
^
:14:错误:类型不匹配;
找到:Char('c')
必需:(字符,整数)
案例xs:+('c',3)=>println(“匹配”)
我错过了什么吗?如果有正确的方法可以做到这一点吗

scala版本是2.11.8


谢谢

您需要用括号括起附加的一对。方法:+接受一个参数。如果没有额外的括号,则假定有两个参数

list match {
     case xs :+ (('c', 3)) => println("Matched")
     case _ => println("Not mathed")
  }