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.
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.