Reputation: 11
I'm still learning the basics and I have a question.
I have a function
def reverse(s: String): String = {
s.reverse
}
Now I have a List[String] and I want to reverse each String element. I've tried foreach, but it seems to return Unit, not String. So, I want a List[String] with the same elements, but the strings reversed.
List(abcd, efgh) becomes List(dcba, hgfe).
What I have now:
def reverse(ls : List[String]):List[String] = {
List(ls.foreach (reverse))
}
Upvotes: 1
Views: 2586
Reputation: 62835
Use map method:
List("abcd", "efgh").map(s => reverse(s))
Or simply:
List("abcd", "efgh").map(reverse)
Unlike foreach which is here for side effects (like printing things out) map does returns result.
Upvotes: 8