Create a List that contains elements of different data types

Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-26 23:42:12 Viewed : 178

In Scala, you can create a List that contains elements of different data types, including both strings and integers. Here are examples of creating such a mixed-type List:

1. Using List Constructor:

You can create a List with mixed types using the List constructor by providing elements of different types:

val mixedList = List("Alice", 42, "Bob", 30, "Carol", 28)

In this example, mixedList contains strings and integers.

2. Using :: (Cons) Operator:

You can also build a mixed-type List by adding elements using the :: operator:

val mixedList = "Alice" :: 42 :: "Bob" :: 30 :: "Carol" :: 28 :: Nil

In this example, Nil represents an empty list, and the :: operator is used to prepend elements to it.

3. Using List[Any]:

If you want to explicitly specify the type of the List as a mix of different types, you can use List[Any]:

val mixedList: List[Any] = List("Alice", 42, "Bob", 30, "Carol", 28)

Here, mixedList is explicitly declared as a List[Any], which allows it to hold elements of any type.

Accessing Elements in a Mixed-Type List:

To access elements in a mixed-type List, you can use indexing and pattern matching:

val name = mixedList(0) // Access the first element val age = mixedList(1) // Access the second element val name2 = mixedList(2) // Access the third element mixedList.foreach { case s: String => println(s"A string: $s") case i: Int => println(s"An integer: $i") case _ => println("Other type") }

In this code, we access elements by index and use pattern matching to differentiate between string and integer elements.


A string: Alice An integer: 42 A string: Bob An integer: 30 A string: Carol An integer: 28

This demonstrates how you can create a mixed-type List in Scala, access its elements, and work with elements of different data types within the same list.

Related Articles

Leave a Comment: