Klasher
Klasher

Reputation: 11

Reverse each element in List[String] in Scala

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

Answers (2)

Atiq
Atiq

Reputation: 396

try this,

List("abcd", "efgh").reverse

Upvotes: 0

om-nom-nom
om-nom-nom

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

Related Questions