I am trying to get the hang of the flatMap
implementation in Scala. Based on the definition in Scala programming
Function returning a list of elements as its right argument. It applies the function to each list and returns the concatenation of all function results.
Now to understand this, I have following implementations
val listwords = List(List("abc"),List("def"),List("ghi"))
val res2 = listwords flatMap (_+"1")
println(res2) //output- List(L, i, s, t, (, a, b, c, ), 1, L, i, s, t, (, d, e, f, ), 1, L, i, s, t, (, g, h, i, ), 1)
val res3 = listwords flatMap (_.apply(0).toCharArray())
println(res3) //output- List(a, b, c, d, e, f, g, h, i)
Looking at first output which drives me crazy, why is List[List[String]]
treated like List[String]
?
After all with answer for above question, someone please help me to perform an operation which needs to pick the first character of the first string of each inner and result in a List[Char]
. So given the listwords
, I want the output to be List('a', 'd', 'g')
.