Search code examples
arraysstringkotlinsplitstring-function

Kotlin String.split().filterIndexed() is returning empty list with size 1


fun main() {

val delDetails = "2-hello,3-world,4-why,5-is,6-it,7-like,8-this"

val delDetailEmpty = ""
val delPositions = delDetailEmpty.split("-",",").filterIndexed { index, _ -> index % 2 ==0}.toMutableList()

println(delPositions.size) //it returns empty list [] with size 1
println(delDetailEmpty.toList().size) //this returns empty list [] with size 0
}

println(delPositions.size) returns empty list [] with size 1

whereas, println(delDetailEmpty.toList().size) this returns empty list [] with size 0


Solution

  • First of all, an empty list will always have size of zero.

    You are using kotlin's builtin extension functions. Their functionalities differ from case to case. You can examine the actual code by clicking on the extension function.

    println(delPositions.size) //it returns empty list [] with size 1

    CharSequence.split(...) returns a list with an empty string in your case but not an empty list. So, the list have size of 1.

    println(delDetailEmpty.toList().size) //this returns empty list [] with size 0

    String.toList() returns an empty list of Char for an empty string. This list here will have size of 0.

    Hope, it helps.