Home > Software engineering >  filter behaviour - kotlin
filter behaviour - kotlin

Time:01-15

Why does this code give the result of "[]" if "J" is given? How does "filter" work in it?

var letter = readLine()!![0]
val names = arrayOf("John", "David", "Amy", "James", "Amanda")`
val res = names.filter{ it.substring(0,1).equals(letter)  }`
println(res)`

CodePudding user response:

filter returns all the elements of the list that satisfies the given predicate.

In this case, the predicate is it.substring(0,1).equals(letter), where it is a given element of the list. As a matter of fact, this can never be satisfied, because it.substring returns a String, but letter is a Char. You are comparing objects of completely different types.

Assuming you want to find all the names that start with letter, you should compare the same types - get the first letter of it as a Char using [0] or first() etc.

val res = names.filter { it.first() == letter }

Additional notes:

  • it is more idiomatic to compare with ==, rather than equals.
  • letter can be a val, instead of var.
  • Since Kotlin 1.6, you can use readln() instead of readLine() to avoid the !! operator.

Alternatively, as lukas.j suggested, use startsWith:

val res = names.filter { it.startsWith(letter) }
  • Related