Is there any way to avoid the cast here? There is ...
# getting-started
m
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
No, not unless you were to also have subclasses of
Foo
that concretely specified
Bar
member types
m
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
or
when (it.bar) { is ... }
m
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
I do need the rest of Foo unfortunately
But that gave me an idea
A little clunky though, but works
s
I don't know if that really buys you much readability tbh
m
Yeah, it probably doesn't
s
it also involves
n
more allocations
m
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
ł
image.png
m
I still need the other properties of
Foo
, which is why I couldn’t just map it to
bar
ł
now I see what you mean. Maybe this would help
image.png
s
that's just a variation on the solution Marcin shared above... did you read the thread?
ł
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
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