The Artima Developer Community
Sponsored Link

Programming in Scala Forum
Chapter 15 Example Issue

1 reply on 1 page. Most recent reply: Dec 24, 2008 11:56 AM by Zemian Deng

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Daniel Hinojosa

Posts: 1
Nickname: 62988
Registered: Oct, 2008

Chapter 15 Example Issue Posted: Dec 14, 2008 12:10 AM
Reply to this message Reply
Advertisement
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)

scala> isStringArray(d)
res1: java.lang.String = yes


Zemian Deng

Posts: 49
Nickname: zdeng
Registered: Jan, 2008

Re: Chapter 15 Example Issue Posted: Dec 24, 2008 11:56 AM
Reply to this message Reply
Daniel,

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"
}
}


As to why Scala compiler do the auto boxing to array, you can get a detail explanation from this post: http://www.drmaciver.com/2008/06/scala-arrays

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.

Flat View: This topic has 1 reply on 1 page
Topic: Is there a way to "export" the compiled class files into runnable jar? Previous Topic   Next Topic Topic: Scala is not friendly with space, and if-without-else

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use