Currently, I am learning Scala and reading this book Programming in Scala and which says, " Unlike an array or list, a tuple can hold objects with different types." For example, the following tuple contain Int, String and Float.
val tup = (1, "hello", 4.4)
Again, the book say, "If you want to have any type of element in list/array, then you can use Any Datatype."
val list = List[Any](1, "hello", 4.4)
So, what is the difference between above these 2 approaches? what are the benefit of one over another?
Any
is a data-type , just likeInt
orString
, but different from them.Tuple
is a container, which can hold multiple data-types, i.e. it can contain vals of different data-types, but the type of theTuple
will depend upon how many elements are there in theTuple
, so for example:But the type of each of the elements in the
Tuple
will be maintained.Any
on the other hand, is like a homegenous data-type in which there's no unique type identity of the elements, be it aString
orInt
orNull
type initially, will be converted to a single data-typeAny
and will lose all type-information.Update:
The difference between a
Tuple
and aList[Any]
is that aTuple
can hold elements of multiple data types, still maintaining the data type of the individual elements.While a
List
orArray
can only hold elements of a single data type, so aList[Any]
will consist of all elements of typeAny
, so it'll basically convert all the elements (irrespective of their earlier data-type) toAny
.I don't agree with PawelN
or
results in:
Hence, no casting is needed when you access an item in a List or an Array of Any. Of course, I'd be suspicious of design of code that is using such a thing.
The main point of a Tuple, is for a function to be able to return arbitrary numbers of objects of different types. This is much lighter weight then creating a class every time you need to return multiple values at the cost of some type safety.
tup
has type(Int, String, Double)
, so you can get data back with its correct type:tup._1
has typeInt
.list
has typeList[Any]
, so you've lost all type information:list(0)
's type isAny
.Don't use
Any
(orList[Any]
, etc.) unless you have to; certainly don't use it when a tuple will do.Tuples are type safe and with List[Any] you have to cast element to appropriate type.
Your tuple is a class of type Tuple3[Int, String, Double].