Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Tuple and List[Any] in Scala?

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?

like image 732
Ra Ka Avatar asked Dec 01 '16 07:12

Ra Ka


1 Answers

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.

like image 83
Alexey Romanov Avatar answered Nov 10 '22 07:11

Alexey Romanov