Note that there is already defined function:

scala> val x = "scala is awesome"
x: java.lang.String = scala is awesome

scala> x.reverse
res1: String = emosewa si alacs

But if you want to do that by yourself:

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

or (sometimes it is better to use until, but probably not in that case)

def reverse(s: String) : String =
(for(i <- s.length until 0 by -1) yield s(i-1)).mkString

Also, note that if you use reversed counting (from bigger one to less one value) you should specify negative step or you will get an empty set:

scala> for(i <- x.length until 0) yield i
res2: scala.collection.immutable.IndexedSeq[Int] = Vector()

scala> for(i <- x.length until 0 by -1) yield i
res3: scala.collection.immutable.IndexedSeq[Int] = Vector(16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Answer from om-nom-nom on Stack Overflow
🌐
24 Tutorials
24tutorials.com › scala › reversal-string-scala-using-recursive-function
Reversal of string in Scala using recursive function - 24 Tutorials
July 21, 2018 - Reversal of String in Scala using recursive function – object reverseString extends App { val s = “24Tutorials” print(revs(s)) def revs(s: String): String = { // if (s.isEmpty) “” if (s.length == 1) s else revs(s.tail) + s.head //else revs(s.substring(1)) + s.charAt(0) } } } Output: slairotuT42
🌐
Medium
medium.com › binary-dreams › from-java-to-scala-tail-recursion-a6acdd71a94d
From Java to Scala: Tail Recursion | by Erik Lundqvist | Binary Dreams | Medium
January 19, 2014 - We will also take advantage of the @tailrec annotation which tells the compiler to expect tail recursion and throw an error if that is not the case. @scala.annotation.tailrec def reverse_tail(s: String, r: String): String = { if (s == null) return null if (s.tail.isEmpty) return s.head + r reverse_tail(s.tail, s.head + r) }
🌐
GeeksforGeeks
geeksforgeeks.org › scala › how-to-reverse-a-string-in-scala
How to reverse a String in Scala? - GeeksforGeeks
July 23, 2025 - Otherwise, it recursively calls itself with the tail of the string s (i.e., all characters except the first one) and appends the first character of s to the result of the recursive call. This process effectively reverses the string.
🌐
Aalto
algorithms.cs.aalto.fi › Teaching › CS-A1120 › 2018 › notes › round-recursion--recursion.html
Recursion and tail recursion recalled — CS-A1120 Programming 2, Spring 2018
Our plan is to also introduce some new terminology (call-stacks and the expansion of function calls) so you may want to read through this part even if you have done all the programming exercises on recursion in the “Programming 1” course. Let us first recall the palindrome example from round 11.3 of “Programming 1” course. A palindrome is a word or sentence that reads the same when read backwards or forwards. For example, the following are palindromes: ... That is, a string is a palindrome if, after omitting spaces and punctuation symbols (”,”, ”!” and so on), the string remains the same when written backwards.
🌐
Scala Algorithms
scala-algorithms.com › ReverseAStringWords
Reverse a String's words efficiently (FP Scala algorithm)
February 4, 2021 - An efficiency portion of this algorithm comes from the fact that rather than appending every character that we come across to an existing string, and thus ending up with allocations of a new String per character, we can extract out the positions of the spaces, and come up with the shape of our target String by describing it in terms of the edges and where the spaces are. (this is © from www.scala-algorithms.com) ... Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it. Get fixed-length sliding sub-sequences (sliding windows) from another sequence · A state machine is the use of `sealed trait` to represent all the possible states (and transitions) of a 'machine' in a hierarchical form.
🌐
GitHub
gist.github.com › lobster1234 › 5036770
Reverse a String - Scala · GitHub
Reverse a String - Scala · Raw · ReverseString.scala · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Baeldung
baeldung.com › home › scala collections › different ways to reverse a sequence in scala
Different Ways to Reverse a Sequence in Scala | Baeldung on Scala
March 18, 2024 - This has all the advantages of the tail-recursive method but is simpler to write. All we have to do is define the initial state of the folded result (an empty sequence for us) and a function that transforms an intermediate result and an element from the original collection into a new intermediate result. We can test the functionality of our methods using the powerful ScalaTest framework. Let’s start with two generic approaches that test reversing small and big collections, respectively:
Find elsewhere
🌐
Thedigitalcatonline
thedigitalcatonline.com › blog › 2015 › 04 › 07 › 99-scala-problems-05-reverse
The Digital Cat - 99 Scala Problems 05 - Reverse a list
The first solution, conversely, gave the result of the recursion as input to the :::() method. Folding may greatly simplify the solution. Remember that foldLeft() is a method of List objects that visits each element in the list, applying a given function. The first use of the function receives the initial value passed to foldLeft(), while successive calls receive the result of the previous call. def reverse[A](ls: List[A]): List[A] = ls.foldLeft(List[A]()) { (r, h) => h :: r }
🌐
IncludeHelp
includehelp.com › scala › reverse-a-string.aspx
Scala program to reverse a string
object myObject { def reverseString(newString: String): String = { var revString = "" val n = newString.length() for(i <- 0 to n-1){ revString = revString.concat(newString.charAt(n-i-1).toString) } return revString } def main(args: Array[String]) { var newString = "IncludeHelp" println("Reverse of '" + newString + "' is '" + reverseString(newString) + "'") } }
🌐
Baeldung
baeldung.com › home
Reversing Strings in Scala | Baeldung on Scala
March 14, 2024 - The most naive approach is to use a loop in reverse: scala> val s = "abcde" s: String = abcde scala> (for(i <- 0 to s.size - 1) yield s(s.size - 1 - i)).mkString res0: String = edcba
🌐
W3Resource
w3resource.com › scala-exercises › string › scala-string-exercise-16.php
Scala Programming: Reverse every word of a given string - w3resource
August 19, 2022 - object Scala_String { def WordsInReverse(str1: String): String = { val each_words = str1.split(" "); var revString = ""; for (i <- 0 to each_words.length - 1) { val word = each_words(i); var reverseWord = ""; for (j <- word.length - 1 to 0 by -1) { reverseWord = reverseWord + word.charAt(j); } revString = revString + reverseWord + " "; } revString; } def main(args: Array[String]): Unit = { val str1 = "This is a test string"; println("The given string is: " + str1); println("The new string after reversed the words: " + WordsInReverse(str1)); val str2 = "The Scala Programming Language"; println("The given string is: " + str2); println("The new string after reversed the words: " + WordsInReverse(str2)); } }
🌐
GitHub
gist.github.com › kpmatta › dfaf2cae78bddcf6d0c974f8d362b2b6
Scala List reverse with recursive way · GitHub
Scala List reverse with recursive way. GitHub Gist: instantly share code, notes, and snippets.
🌐
Programming Idioms
programming-idioms.org › idiom › 41 › reverse-a-string › 1450 › scala
Reverse a string, in Scala
runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } t := string(runes) ... func reverse(s string) string { if len(s) <= 1 { return s } var b strings.Builder b.Grow(len(s)) for len(s) > 0 { r, l := utf8.DecodeLastRuneInString(s) ...
🌐
W3Resource
w3resource.com › scala-exercises › function › scala-function-exercise-4.php
Scala function: Reverse a given string
object StringReverser { def reverseString(str: String): String = { str.reverse } def main(args: Array[String]): Unit = { val input = "Scala, Code!" val reversed = reverseString(input) println(s"The reversed string of $input is: $reversed") } }
Top answer
1 of 2
2

You can use the following definition:

def printNames(names: List[String]): String = {
  if(names.isEmpty) ""
  else printNames(names.tail) + " " + names.head
}

Note that this implementation is not tail recursive and cannot be optimized by scala compiler. I strongly advise using an accumulator for the resulting String.

Luis Miguel Mejía Suárez suggests using StringBuilder to avoid expensive String concatenation:

def printNames(names: List[String]): StringBuilder = {
  if(names.isEmpty) new StringBuilder("")
  else printNames(names.tail).append(" ").append(names.head)
}
2 of 2
0
def printNames(names: List[String]): String = names.reverse.mkString(" ")

You can reverse the name list and then use mkString with space as a separator. The above one can be used to achieve the same without recursion, as mkString by default uses StringBuilder.

As you were looking for a tail-recursive solution

import scala.annotation.tailrec

def printNames(names: List[String]): String = {
  @tailrec
  def printNamesHelper(
      names: List[String],
      acc: StringBuilder = new StringBuilder("")
  ): String = {
    names match {
      case Nil          => acc.toString.trim
      case head :: tail => printNamesHelper(tail, acc.append(head).append(" "))
    }
  }
  printNamesHelper(names)
}

def printNamesReverse(names: List[String]): String = {
  @tailrec
  def printNamesReverseHelper(
      names: List[String],
      accum: List[String] = List.empty
  ): String = {
    names match {
      case Nil          => printNames(accum)
      case head :: tail => printNamesReverseHelper(tail, head :: accum)
    }
  }
  printNamesReverseHelper(names)
}

printNames(List("Adam", "Framk"))
printNamesReverse(List("Adam", "Framk"))

Added scastie snippet below:

<script src="https://scastie.scala-lang.org/shankarshastri/0dxWt7K3S8CkkAffliLICQ/7.js"></script>

🌐
Scala Users
users.scala-lang.org › question
Reflection + String + reverse - Question - Scala Users
February 20, 2018 - Hello to everyone, I need to resolve this question, I trying to execute with reflection some methods of String class, like ‘reverse’ but is not possible. Do you know if there any way to execute this? . Thank you… ;). classOf[String].getMethod(“reverse”).invoke(result).asInstanceOf[String] Regards, JC
🌐
Heichwald
heichwald.github.io › 2016 › 01 › 17 › reverse-words-in-place-scala
Reverse in place words order in a string in Scala · my dev blog
January 17, 2016 - A string is an immutable object but it is easy to convert once from a string to an array of chars · /** * Reverse array in place from start to end inclusive */ def reverse(arr: Array[Char], start: Int, end: Int) = { if (end > start) { (0 to (end - start)/2) foreach { i => val iStart = i + start val iEnd = end -i val b = arr(iStart) arr(iStart) = arr(iEnd) arr(iEnd) = b } } }