簡體   English   中英

在 Scala 中更好地對匹配進行類型檢查

[英]Better type checking on match in Scala

scala> class A
defined class A

scala> class B
defined class B

scala> val a: A = new A
a: A = A@551510e8

scala> a match {
     | case _: B => println("unlikely")
     | case _ => println("no match")
     | }
no match

在上面的例子中,編譯器不應該告訴我其中一種情況永遠不會匹配嗎? 最近一個稍微復雜的例子讓我發現了,這導致了一個應該被編譯器捕獲的不必要的錯誤。

編輯:

只是為了更清楚地了解這個問題。 由於某種我看不到的原因,這在 Scala 中是不可能的嗎? (我可以理解這些類型是否使用了泛型並且類型擦除導致了問題,但這看起來很簡單。)如果這不是不可能的,那么是否有正當理由這不在 Scala 中? 如果沒有,什么時候添加? ;)

目前,僅對案例類構造函數模式進行詳盡和冗余檢查。 原則上,編譯器也可以為其他類型的模式執行此操作。 但是必須在 SLS 中具體說明進行了哪些測試。 考慮到不同模式類之間的交互,這看起來可行但並非微不足道。 因此,總而言之,這是 Scala 中可以從進一步貢獻中受益的領域之一。

如果您使用案例類,編譯器會警告您(實際上編譯失敗):

scala> case class A()
defined class A

scala> case class B()
defined class B

scala> val a = A()
a: A = A()

scala> a match {
     | case A() => println("A")
     | case B() => println("B")
     | case _ => println("_")
     | }
<console>:13: error: constructor cannot be instantiated to expected type;
 found   : B
 required: A
       case B() => println("B")

我檢查了 Scala 2.13.3 ,我們收到了fruitless type test的警告:

scala> a match {
     | case _:B => println("B")
     | case _ => println("no match")
     | }
       case _:B => println("B")
              ^
On line 2: warning: fruitless type test: a value of type A cannot also be a B
no match

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM