编号因数字类型上的模式匹配而失败

时间:2015-09-14 16:28:43

标签: scala pattern-matching

以下是我的代码,我试图检查a中每个t的类型。

for (a <- t) {
  for (b <- a) {
    def get_type(obj: Any) = obj match {
      case n: Number => println("n is an integer equal to: ")
      case s: String => println("$s is a String")
      case _ => println("Error: unmatched type")
    }
    get_type(b)
  }
}

但是,我收到了这个错误:

[error] /home/plard/Desktop/modified_peacock_src/gps_example/../template/Actors/Save.scala:82: scrutinee is incompatible with pattern type;
[error]  found   : Number
[error]  required: String
[error]                         case n: Number => println ("n is a Number equal to: ")
[error]                                 ^
[error] one error found

有谁知道它会发生什么原因,好吗?

1 个答案:

答案 0 :(得分:2)

当我以这种方式使用它时,您的代码按预期工作:

val t = new ArrayBuffer[Array[String]]
t += Array("1", "2", "3")                         
t += Array("4", "5", "6")
for (a <- t)
  for (b <- a) {
    def get_type(obj: Any) = obj match {
      case n: Number => println("n is an integer equal to: ")
      case s: String => println("$s is a String")
      case _         => println("Error: unmatched type")
  };
  get_type(b)
}                                             

输出如下:

n is a String 
n is a String
n is a String
n is a String
n is a String 
n is a String

如果稍微简化代码,可以创建相同的错误:

  1 match {
    case n: Number => println("n is an integer equal to: ")
    case s: String => println("$s is a String")
    case _         => println("Error: unmatched type")
  }

这实际上应该导致两个错误:

scrutinee is incompatible with pattern type;  found   : Number  required: Int
scrutinee is incompatible with pattern type;  found   : String  required: Int

但是,您在上面提供的代码中不会发生这种情况,因为obj的类型为Any而不是Int