huehnerlady
08/25/2020, 11:14 AMpublic fun <T : Any> Iterable<T?>.filterNotNull(): List<T> {
return filterNotNullTo(ArrayList<T>())
}
So I expect I can use it with a non-nullable list with nullable items, and I get a non-nullable list with just non-nullable items back.
But when I use this method like so:
fun List<String?>?.extract(): List<String> =
this?.filterNotNull().map {
"foo"
}.toList()
I get a compiler error as shown in my screenshot.
Why is this the case? I would have expected that the output is a non-nullable list, at least that is what I read out of the signature?
I am using kotlin 1.3.72bezrukov
08/25/2020, 11:19 AMSo I expect I can use it with a non-nullable list with nullable itemsthis is correct But the issue is that you wrote an extension for nullable list (List<String?>*?*)
dmitriy.novozhilov
08/25/2020, 11:19 AM?.
returns nullable object
Correct code for your case should look smth like this:
fun List<String?>?.extract(): List<String> =
this?.filterNotNull()?.map { "foo" } ?: emptyList()
huehnerlady
08/25/2020, 11:23 AMhuehnerlady
08/25/2020, 11:23 AMthis?.filterNotNull()
it should be smartcasted to a non-nullable object when calling the filter function I thought?dmitriy.novozhilov
08/25/2020, 11:28 AMfun Int?.foo(): String = "hello"
fun Int.foo(): String = "world"
fun test(s: String?) {
val message = s?.length.foo()
println(message)
// what should be printed?
// "hello", "world" or "null"?
// currently it is unequivocally prints "hello"
}
huehnerlady
08/25/2020, 11:29 AM