0
0
KotlinHow-ToBeginner · 3 min read

How to Reverse String in Kotlin: Simple Guide

In Kotlin, you can reverse a string easily by using the reversed() function on a string variable. This function returns a new string with characters in reverse order without changing the original string.
📐

Syntax

The syntax to reverse a string in Kotlin is simple. You call the reversed() function on any string instance.

  • string.reversed(): Returns a new string with characters reversed.
kotlin
val original = "hello"
val reversed = original.reversed()
💻

Example

This example shows how to reverse a string and print both the original and reversed strings.

kotlin
fun main() {
    val original = "Kotlin"
    val reversed = original.reversed()
    println("Original: $original")
    println("Reversed: $reversed")
}
Output
Original: Kotlin Reversed: niltoK
⚠️

Common Pitfalls

One common mistake is trying to reverse a string by modifying it directly, but strings in Kotlin are immutable. The reversed() function returns a new string and does not change the original.

Another mistake is forgetting that reversed() returns a new string, so you must assign or use the returned value.

kotlin
/* Wrong way: Trying to change original string directly (won't compile) */
// original.reverse() // No such function

/* Right way: Use reversed() and assign result */
val original = "abc"
val reversed = original.reversed()
📊

Quick Reference

Remember these points when reversing strings in Kotlin:

  • reversed() returns a new reversed string.
  • Original string remains unchanged.
  • Works on any string variable.

Key Takeaways

Use the built-in reversed() function to reverse strings in Kotlin.
Strings are immutable; reversed() returns a new string without changing the original.
Always assign or use the result of reversed() to get the reversed string.
The syntax is simple: val reversed = original.reversed().
This method works for any string variable in Kotlin.