以下是我的代码,我试图检查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
有谁知道它会发生什么原因,好吗?
答案 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
。