为什么编译器会为同样的错误发出警告和错误?

时间:2017-12-29 17:53:03

标签: scala

在以下代码中,我将p1Person(匹配)和String匹配,但不匹配。为什么编译器同时提供警告和错误?为什么不给它们中的一个呢?

scala> case class Person(fname:String, lname:String, age:Int)
defined class Person

scala> val p1 = Person("manu","chadha",37)
p1: Person = Person(manu,chadha,37)
scala> p1 match {
     | case p:Person =>println(s"${p.fname},${p.lname},${p.age}");
     | case s:String =>println(s) //I know this will not match
     | }
<console>:17: warning: fruitless type test: a value of type Person cannot also be a String (the underlying of String)
       case s:String =>println(s)
              ^
<console>:17: error: pattern type is incompatible with expected type;
 found   : String
 required: Person
       case s:String =>println(s)
              ^

为什么这会起作用?

scala> p1 match {
     | case p:Person =>println(s"${p.fname},${p.lname},${p.age}");
     | case _ => println("something else")
     | }
manu,chadha,37

1 个答案:

答案 0 :(得分:2)

1. fruitless type test警告由检查程序引发,请参阅:CheckabilityChecker检查程序警告可能的问题。 为什么只是警告?请参阅以下示例:

val res = Some(1).isInstanceOf[String] // Warning:fruitless type test: a value of type Some[Int] cannot also be a String (the underlying of String)

res始终为false,但它仍然是合法语法,因此编译器只会针对此方案抛出警告。< / p>

2. error: pattern type is incompatible...按类型Infer引发,在您的示例中,它必定是错误,因为Person不能是String类型,因此此类型推断错误将被抛出。

相关问题