I have a Seq
of objects like Seq(x1, x2, x3, x4)
and I want to tranform it to Seq(y1, y2, y3, y4)
What is the most efficient way of doing so
Right now I am
val seq1 = Seq(x1, x2, x3......)
var seq2 = Seq[MyType2]()
for (myObj <- seq1) {
seq2 = seq2 : myObj.tranformToType2
}
The problem is that the scala doc says
https://www.scala-lang.org/api/2.12.x/scala/collection/Seq.html
a new sequence consisting of all elements of this sequence followed by elem.
so I was wondering what is the most idiomatic/efficient way of tranforming a list of object to another list of object
CodePudding user response:
The code you wrote is Scala imperative style, but Scala aims to be a functional language.
The functional approach being:
val seq2 = seq1.map(myObj => myObj.tranformToType2)
// Or shorter:
val seq2 = seq1.map(_.tranformToType2)
map
is one of the most useful operation in function programming. You will see that you'll use it everywhere when you need to transform something into something else.
As a rule of thumb, whenever you see a var
and a for
loop, this is smelly and you should ask yourself how do I do this the functional way?
CodePudding user response:
map
is the function that you are looking for. Check the docs for details.
A simplistic example:
case class MyType1(x: String)
case class MyType2(x: Int)
val ls: Seq[MyType2] = Seq(MyType1("hello"), MyType1("world")).map(mt1 => MyType2(mt1.content.length))