https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Marcin Wisniowski

11/28/2023, 6:53 PM
Is there any way to avoid the cast here? There is
filterIsInstance()
but it only works for the root element, not an inner property.
s

Shawn

11/28/2023, 6:57 PM
No, not unless you were to also have subclasses of
Foo
that concretely specified
Bar
member types
m

Marcin Wisniowski

11/28/2023, 6:59 PM
I guess I can just not use the
filter
and instead have an if check in the
forEach
, which gets me a smart cast.
s

Shawn

11/28/2023, 6:59 PM
or
when (it.bar) { is ... }
m

mkrussel

11/28/2023, 7:03 PM
If you only need it.bar and not the rest of Foo you can do
Copy code
listOf<Foo>()
   .mapNotNull { it.bar as? Bar.A)
   .forEach { a ->
   }
m

Marcin Wisniowski

11/28/2023, 7:08 PM
I do need the rest of Foo unfortunately
But that gave me an idea
A little clunky though, but works
s

Shawn

11/28/2023, 7:11 PM
I don't know if that really buys you much readability tbh
m

Marcin Wisniowski

11/28/2023, 7:11 PM
Yeah, it probably doesn't
s

Shawn

11/28/2023, 7:11 PM
it also involves
n
more allocations
m

mkrussel

11/28/2023, 7:14 PM
I would probably just go back to a basic for loop with an if statement unless this was going to feed into more operators than just the forEach.
👆 2
ł

Łukasz Gendek

11/29/2023, 2:37 PM
image.png
m

Marcin Wisniowski

11/29/2023, 4:41 PM
I still need the other properties of
Foo
, which is why I couldn’t just map it to
bar
ł

Łukasz Gendek

11/29/2023, 7:32 PM
now I see what you mean. Maybe this would help
image.png
s

Shawn

11/29/2023, 7:45 PM
that's just a variation on the solution Marcin shared above... did you read the thread?
ł

Łukasz Gendek

11/29/2023, 8:30 PM
in my opinion this proposition is a bit better, please notice that that • filterSecondNotNull is a generic, library method, and could be reused - it is not foo/bar related, in my opinion it doesn't make the code more complex, but opposite, it takes the complexity away • what is left is much simplier now: the map expression is clearer, it is just an expression, with no statements e.g. return@mapOrNull
👍 1
p

phldavies

11/30/2023, 9:29 AM
Given the order of the pair isn't important in this chain, you could just as easily use
.mapNotNull { (it.bar as? Bar.A)?.to(it) }
👍 2
🆒 1