型変数のパターンマッチがうまく機能しない場合
code:scala
scala> var obj: AnyRef = List("aaa")
obj: AnyRef = List(aaa)
scala> obj match {
| case v:ListInt => println("ListInt") | }
実際はList[String]なのに、List[Int]と誤判定している。
これはコンパイラから見た場合に両者の区別が(型消去によって)見分けがつかないため。 コンパイラオプション -unchecked で、上記のケースがあった際に警告を出すことができる。
code:txt
<console>:14: warning: non-variable type argument Int in type pattern ListInt (the underlying of ListInt) is unchecked since it is eliminated by erasure case v:ListInt => println("ListInt") ^
<console>:15: warning: non-variable type argument String in type pattern ListString (the underlying of ListString) is unchecked since it is eliminated by erasure ^
<console>:15: warning: unreachable code
^
List[T] のような型変数をマッチさせたい場合は v:List[_] としてワイルドカードにする。
→ じゃあ_の型はどのようにして見分けたらいいの?🤔