Tuesday, October 4, 2016

Typed Pattern, Type Erasure : Example...

scala> ////////////////////////////////////////////////////////////////

scala> //  Typed Pattern : Pattern Matching a Type

scala> ////////////////////////////////////////////////////////////////

scala> def patternFn(x: Any) = x match {
     |     //
     |     case b: List[_] => println("List...")
     |
     |     // This do not work because of type erasure #318
     |     case c: Map[Int, Int] => println("This is wrong...")
     |
     |     case d: Map[_, _] => println("Map: This does work")
     |
     |     // We dot have issue of Type Erasure with Array
     |     case e: Array[Int] => println("Array of Int...")
     |
     |     case f: Array[_] => println("Array of other types...")
     | }
<console>:28: warning: non-variable type argument Int in type pattern scala.collection.immutable.Map[Int,Int] (the underlying of Map[Int,Int]) is unchecked since it is eliminated by erasure
           case c: Map[Int, Int] => println("This is wrong...")
                   ^
<console>:30: warning: unreachable code
           case d: Map[_, _] => println("Map: This does work")
                                       ^
patternFn: (x: Any)Unit

scala>

scala> // Not expected result because of type erasure

scala> patternFn(Map[Int, String](1 -> "a", 2 -> "b"))
This is wrong...

scala> // Expected result : For Array we do not have the issue of

scala> //      type erasure

scala> patternFn(Array[Int](1, 2, 3))
Array of Int...

scala> patternFn(Array[Double](1.2, 2,2))
Array of other types...