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

Scala 为什么编译器会对相同的错误发出警告和错误?,scala,Scala,在下面的代码中,我正在将p1与Person(将匹配)和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&g

在下面的代码中,我正在将
p1
Person
(将匹配)和
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)
              ^

1.
无结果的型式试验
警告是由检查程序抛出的,请参阅:,检查程序只是警告可能的问题那么为什么只是警告?请参见以下示例:

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
,但它仍然是合法语法,因此编译器只会在这种情况下抛出警告


2.
错误:模式类型不兼容…
是按类型抛出的,在您的示例中,这一定是一个错误,因为
Person
不能是
String
类型,因此将抛出此类型推断错误。

为了让事情更有趣,如果您尝试模式匹配字符串,但第一次匹配时有两个大小写,您只会收到一个错误,而不会收到一个警告。因为
\uu
将匹配类型
Person
中的任何其他类型构造函数。由于这是唯一的情况,
\uuu
是冗余的。
\uu
不应该匹配不同的类型,而是匹配相同类型的实例(案例类)。我认为它只是懒散地在最后一个案例中没有警告无法访问的代码。这是一个很好的例子。通常情况下,您不会看到同一位置的两条消息,但在这种情况下,警告首先出现,然后会发出更高优先级的错误。那个检查器知道它在一个模式中,所以它可以有效地抑制那个一个警告
String(String的底层)
也是一个不错的选择。
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)