The Artima Developer Community
Sponsored Link

Programming in Scala Forum
A list containing strings and Ints?

1 reply on 1 page. Most recent reply: Dec 20, 2009 1:23 AM by Andy Spaven

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
Vimal Goel

Posts: 1
Nickname: vgoel9
Registered: Oct, 2009

A list containing strings and Ints? Posted: Dec 3, 2009 10:26 AM
Reply to this message Reply
Advertisement
In Chapter 3, Step 9:
"Like lists, tuples are immutable,
but unlike lists, tuples can contain different types of elements."
In the code sequence below, I was successfully able to create lists with strings and Ints mixed in.
------------------
val myList = List("one", "two", "three", "four")
val hisList = List("five", "six", 237)
val herList = 11 :: 12 :: "seven" :: Nil
val bigList = myList ::: hisList ::: herList
val biggerList = 99 :: bigList
println(biggerList)
------------------
Please explain. Thanks.


Andy Spaven

Posts: 1
Nickname: andysp
Registered: Dec, 2009

Re: A list containing strings and Ints? Posted: Dec 20, 2009 1:23 AM
Reply to this message Reply
The difference is that with biggerList the contained values are typed as Any - as biggerList gets created as a List[Any] - so you cannot do the following..

------------------------------
// try to access 'seven' as a string
val myString : String = biggerList(10)
<console>:9: error: type mismatch;
found : Any
required: String
val myString : String = biggerList(10)

// we can only get any "any" out of it
val aValue = biggerList(10)
aValue: Any = seven
------------------------------


but if it were a tuple
------------------------------
val aTuple = (1,2,3,"four",5,6,7)

val text = aTuple._4
text: java.lang.String = four
------------------------------

gives a value that is typed as a string.

Mostly though tuples and lists seem to play different roles for different purposes.

Hope that helps

Flat View: This topic has 1 reply on 1 page
Topic: Book as epub Previous Topic   Next Topic Topic: Still No Spaces/Scale-Out/XTP possible in Scala?

Sponsored Links



Google
  Web Artima.com   

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