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 thanequals. lettercan be aval, instead ofvar.- Since Kotlin 1.6, you can use
readln()instead ofreadLine()to avoid the!!operator.
Alternatively, as lukas.j suggested, use startsWith:
val res = names.filter { it.startsWith(letter) }
