So I have a piece of code that looks like this: ``...
# announcements
p
So I have a piece of code that looks like this:
Copy code
val foo = listOf("foo", "bar", null, "")
    val bar = foo.filter { !it.isNullOrEmpty() }
the compiler is arguing that
bar
is
List<String?>
while my position is that it should be
List<String>
. Am I expecting too much from contracts? And is there a better way to write this?
s
it might also have something to do with the fact that filter is defined as
((T) -> Boolean) -> T
, which makes transforms to the non-null version of
T
kind of a higher effort thing
l
Here's the fixed version:
Copy code
val foo = listOf("foo", "bar", null, "")
val bar: List<String> = foo.asSequence().filterNotNull().filter { it.isNotEmpty() }.toList()
2
s
the best way right now might be to
.filterNotNull()
and then
.filter(String::isNotEmpty)
☝️ 2
making it a sequence if you’ve got a lot of elements
1
p
yeah, I came to the same conclusion as well
val bar = foo.filterNotNull().filterNot { it.isEmpty() }
I am not too happy about this, but it does the correct thing
s
I mean agreed but ¯\_(ツ)_/¯
maybe we’ll eventually get something like
.filterNotNullAnd { ... }
l
You can always suggest a feature like improved contracts for this on kotl.in/issue
p
I should probably do that
k
p
awesome. thanks
s
You can do it in one go with
mapNotNull
👍 1