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?
tup
has type (Int, String, Double)
, so you can get data back with its correct type: tup._1
has type Int
. list
has type List[Any]
, so you've lost all type information: list(0)
's type is Any
.
Don't use Any
(or List[Any]
, etc.) unless you have to; certainly don't use it when a tuple will do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With