Search code examples
androidkotlintrim

Difference between trim{it <= ' '} and trim in kotlin?


trim in kotlin remove space int leading and trailing, but when android studio convert java code to kotlin ,convert trim() in java to trim{it <= ' '} in kotlin when change this to trim,It made no difference. whats difference between trim and trim{it <= ' '}??


Solution

  • According to the docs: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/trim.html

    fun String.trim(): String Returns a string having leading and trailing whitespace removed.

    The it <= ' ' would remove all the 'non printable' characters with ascii code less or equal than space (ascii decimal = 32) as carriage return, line feed...

    I've just tested with many of this characters:

    val kotlin = "\t🙂\t"
    println(kotlin)
       
    val kotlin2 = "\t🙂\t".trim()
    println(kotlin2)
       
    val kotlin3 = "\t🙂\t".trim{it <= ' '}
    println(kotlin3)
    

    this outputs:

        🙂  
    🙂
    🙂
    

    They both clean this characters. And as @AlexeyRomanov states kotlin understands as a whitespace character the ones that return true using the isWhitespace method. So the it <= ' ' is to make it only trim the same chars as java does and not the other whitespace characters according to the Unicode standard.

    If we test for example the \u00A0 character:

    val kotlin4 = "\u00A0🙂\u00A0".trim()
    println(kotlin4)
       
    val kotlin5 = "\u00A0🙂\u00A0".trim{it <= ' '}
    println(kotlin5)
    

    we can see the difference in output:

    🙂
     🙂 
    

    You can test it in the kotlin playground.