I'm doing a simple test to understand why my code wasn't working.
val v = listOf("1", "2", "2", "3")
assertThat((v.filter { equals("2") }).size , `is`(2))
it fails with reason "size is 0"
but when I change it for:
val v = listOf("1", "2", "2", "3")
assertThat((v.filter { it == "2" }).size , `is`(2))
In Java I could do:
.filter(Objects::equals)
It returns the expected result. Anybody can understand why is this behaviour???
What you need to write is
assertThat((v.filter { it.equals("2") }).size , `is`(2))
although note that IntelliJ will immediately suggest substituting the equals
call with ==
if you have the 'Can be replaced with binary operator' inspection enabled.
Also, no you wouldn't be able to write this specific call as .filter(Objects::equals)
in Java, because static Objects#equals
takes 2 parameters, while the method filter
provides only 1 to its lambda argument. But you still can use function references in Kotlin too (with the appropriate functions for the lambda expected). For instance, you could filter all non-blank strings like this:
val v = listOf("1", "", "2", " ", "\t", "3")
println(v.filter(String::isNotBlank))