Hello, I have a problem with an example "isStringArray(x: Any)" on Chapter 15, Page Bottom of page 307.
danno@danno-laptop:~$ scala Welcome to Scala version 2.7.2.final (Java HotSpot(TM) Server VM, Java 1.6.0_11). Type in expressions to have them evaluated. Type :help for more information.
scala> def isStringArray(x: Any) = x match { | case a: Array[String] => "yes" | case _ => "no" | } isStringArray: (Any)java.lang.String
scala> isStringArray(Array("One", "Two")) res0: java.lang.String = no
What I don't understand is, why is res0 = no?
But, when I extract the variable, it works fine?
scala> val d = Array("One", "Two") d: Array[java.lang.String] = Array(One, Two)
I think this is because Scala compiler auto boxed the Array before calling that method, while it won't when doing direct Array assignment. You can see it if you try this: def isStringArray(x: Any) = { println(x.asInstanceOf[AnyRef].getClass) x match { case a: Array[String] => "yes" case _ => "no" } }
Also, as the book have warned on that previous page that Array is an exception and handled extra care in Scala for this type of "type match". And this particular corner case doesn't serve much purpose, because normally if you were to write Scala code, using List or ListBuffer are much preferred than to Array. I normally only use Array when working with existing Java libraries that needs it.