String Reversing in Scala

Playing around today with Scala I’ve created this construct to reverse a string in other than the obvious:

scala> "hello".reverse
res62: String = olleh

that is:

scala> "hello".foldLeft(List[Char]()){(a,b)=>b::a}.mkString("")
res61: String = olleh

breaking it down initially we have the string literal:

scala> "hello"
res1: java.lang.String = hello

then we apply on that literal the foldLeft operation building up on a List of chars:

scala> "hello".foldLeft(List[Char]()){(a,b)=>b::a}
res0: List[Char] = List(o, l, l, e, h)

and finally call the mkString(“”) method on the above to compile a string:

scala> "hello".foldLeft(List[Char]()){(a,b)=>b::a}.mkString("")
res0: String = olleh

Advertisements
By dimitrisli Posted in Scala

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s