Reputation: 397
I have the following List
of tuples in Scala:
var a : List[(Int,String)] = List()
a = a:+((1,"bla bla bla"))
a = a:+((2,"la la la"))
a = a:+((3,"bla la bla"))
which looks like that:
print(a)
List((1,bla bla bla), (2,la la la), (3,bla la bla))
What I wish to do is to apply flatMap
function in order to create a new list from the list a
which contains only the strings from the tuple to which it appends the word "appended". The result should therefore be:
List(bla bla blaappended, la la laappended, bla la blaappended)
Could someone help me understand how I could go about it? I am new to Scala and I can't wrap my head around this. Thanks in advance
Upvotes: 1
Views: 357
Reputation: 22885
You do not want flatMap
you want just a map
, because you only want to perform a one to one transformation.
Also, for this kind of situations pattern matching is very helpful.
(BTW, consider reading all the tour and other basic tutorials)
// Avoid mutability ;)
val list : List[(Int,String)] = List(
1 -> "bla bla bla",
2 -> "la la la",
3 -> "bla la bla"
)
val result = list.map {
case (_, str) => s"${str} appended"
}
Upvotes: 3
Reputation: 26056
You don't need flatMap
, simple map
is enough
val result = a.map(t => t._2 + "appended")
Upvotes: 1