https://kotlinlang.org logo
Title
p

pavel

11/06/2018, 12:07 AM
So I have a piece of code that looks like this:
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

Shawn

11/06/2018, 12:15 AM
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

louiscad

11/06/2018, 12:16 AM
Here's the fixed version:
val foo = listOf("foo", "bar", null, "")
val bar: List<String> = foo.asSequence().filterNotNull().filter { it.isNotEmpty() }.toList()
2
s

Shawn

11/06/2018, 12:16 AM
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

pavel

11/06/2018, 12:17 AM
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

Shawn

11/06/2018, 12:19 AM
I mean agreed but ¯\_(ツ)_/¯
maybe we’ll eventually get something like
.filterNotNullAnd { ... }
l

louiscad

11/06/2018, 12:20 AM
You can always suggest a feature like improved contracts for this on kotl.in/issue
p

pavel

11/06/2018, 12:21 AM
I should probably do that
k

karelpeeters

11/06/2018, 12:27 AM
p

pavel

11/06/2018, 12:27 AM
awesome. thanks
s

spand

11/06/2018, 11:09 AM
You can do it in one go with
mapNotNull
👍 1