0

I am very new to Scala and was trying to understand how we can store values of different types in a collection.

For example, assuming I have the following values with corresponding types:

12 - Int
4.0 - Float
"is the best place to learn and practice coding!" - String

How can I store all the three inputs and perform different logic on each of them?

erip
  • 16,374
  • 11
  • 66
  • 121
neil
  • 149
  • 1
  • 12
  • A great question & answer on the subject - https://stackoverflow.com/questions/11825129/are-hlists-nothing-more-than-a-convoluted-way-of-writing-tuples – bobah Oct 08 '18 at 10:02

2 Answers2

6

There is a bad answer: Seq[Any]. This is a sequence of any type, so you have no information about the members and will need to do a (potentially unsafe) cast or a (potentially non-exhaustive) pattern match again them.

There is a better answer: HList, which is a heterogeneous list, offered by the Shapeless library. This captures type information about each member. See an example here.

There is a best answer: carefully consider whether you need this at all. case classes will tend to be more idiomatic most of the time.

erip
  • 16,374
  • 11
  • 66
  • 121
1
scala> Array(12, 4.0f, "Hello")
res1: Array[Any] = Array(12, 4.0, Hello)

scala> res1.foreach{ case i: Int => println("Integer"); case f: Float => println("Float"); case s: String => println("String")}
Integer
Float
String

However - you should probably heed the advice given by @erip

Terry Dactyl
  • 1,839
  • 12
  • 21