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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.