Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala reverse string

Tags:

scala

I'm a newbie to scala, I'm just writing a simple function to reverse a given string:

def reverse(s: String) : String
  for(i <- s.length - 1 to 0) yield s(i)

the yield gives back a scala.collection.immutable.IndexedSeq[Char], and can not convert it to a String. (or is it something else?)

how do i write this function ?

like image 636
Dzhu Avatar asked Oct 08 '11 23:10

Dzhu


1 Answers

All the above answers are correct and here's my take:

scala> val reverseString = (str: String) => str.foldLeft("")((accumulator, nextChar) => nextChar + accumulator)
reverseString: String => java.lang.String = <function1>

scala> reverseString.apply("qwerty")
res0: java.lang.String = ytrewq
like image 113
Sudheer Aedama Avatar answered Oct 05 '22 04:10

Sudheer Aedama