Avatar of Pfaithful

Pfaithful's solution

to Reverse String in the Kotlin Track

Published at Oct 18 2019 · 0 comments
Test suite


This exercise has changed since this solution was written.

Reverse a string

For example: input: "cool" output: "looc"


Go through the setup instructions for Kotlin to install the necessary dependencies:


Making the test suite pass

Execute the tests with:

$ gradlew test

Use gradlew.bat if you're on Windows

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the @Ignore annotation.


Introductory challenge to reverse an input string https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


import org.junit.Ignore
import org.junit.Test
import kotlin.test.assertEquals

class ReverseStringTest {
    fun testAnEmptyString() {
        assertEquals("", reverse(""))

    fun testAWord() {
        assertEquals("tobor", reverse("robot"))

    fun testACapitalizedWord() {
        assertEquals("nemaR", reverse("Ramen"))

    fun testASentenceWithPunctuation() {
        assertEquals("!yrgnuh m'I", reverse("I'm hungry!"))

    fun testAPalindrome() {
        assertEquals("racecar", reverse("racecar"))

 * Obviously you could just call input.asReversed(), but for these sort of exercises
 * it's more entertaining to try and implement it as if the method didn't exist.
fun reverse(input: String): String = input
        .toCharArray().apply { forEachIndexed { index, _ ->
            this[index] = input[input.length - index - 1]
        } }.joinToString("")

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?