Search code examples
kotlinextension-function

How to write in-place extension-function


fun String.reversed():String{
// return another String..no 
prob
}

fun String.reverse(){
//in-place change this
} 

How to write the String.reverse()?


Solution

  • You can check how the in-place extension function reverse is implemented for MutableList in the Kotlin codebase: https://github.com/JetBrains/kotlin/blob/1.3.50/libraries/stdlib/js/src/generated/_CollectionsJs.kt#L20

    fun <T> MutableList<T>.reverse(): Unit {
        val midPoint = (size / 2) - 1
        if (midPoint < 0) return
        var reverseIndex = lastIndex
        for (index in 0..midPoint) {
            val tmp = this[index]
            this[index] = this[reverseIndex]
            this[reverseIndex] = tmp
            reverseIndex--
        }
    }
    

    In general, you take this instance and call mutating methods on it to modify its content in place.

    However, String class is immutable: it doesn't provide methods to modify its content in place, and, therefore, you cannot write an extension that modifies a string in place either.