简体   繁体   中英

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))
}

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.

尝试这个,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM