'Merging lists in scala

I have to merge these two lists together in a way that results in the 3rd list. I'm not super familiar with Scala that much but I am always interested in learning.

val variable = List("a", "b", "c") | val number = List("1", "2", "3")

When merged and printing each value after, it should result in an output like this

a is equal to 1 b is equal to 2 c is equal to 3

with a list that is now equal to

List("a is equal to 1", "b is equal to 2", "c is equal to 3")

Please help me out



Solution 1:[1]

zip and map would work,

variable.zip(number).map {case (str, int) => s"$str is equal to $int"}

Solution 2:[2]

Alternativly, you could use for-comprehensions

Welcome to Scala 3.1.1 (17, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
                                                                                                          
scala> val variable = List("a", "b", "c")
val variable: List[String] = List(a, b, c)
                                                                                                          
scala> val number = List("1", "2", "3")
val number: List[String] = List(1, 2, 3)
                                                                                                          
scala> for {
     |   str <- variable
     |   n <- number
     | } yield s"$str is equal to $n"
val res0: List[String] = List(a is equal to 1, a is equal to 2, a is equal to 3, b is equal to 1, b is equal to 2, b is equal to 3, c is equal to 1, c is equal to 2, c is equal to 3)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Johny T Koshy
Solution 2 counter2015