Humble Kotlin and Rx solutions (not suggestion)

Note: When I wrote this article I was trying to solve a problem that I thought existed. One day later, I know the problem don’t exist. But hey, it gave me a coding challenge and I learned something from it =)
So I’ll keep it around, with the solutions in the bottom.

Kotlin is a wonderful language, I specially enjoy the “little” things that makes the great difference. Little in the sense that they just provide a human expected behaviour, like smart cast.

Take this example, as a human you understand that after you’ve checked to see if an object is of a specific type you don’t need the redundancy of casting the object directly inside that if-statement to use it properly.

That’s great, but when you get use to have this functionality it is rather painful when it’s not working as expected. And I don’t know if the similar behaviour is intended to work or not. But according to my brains way of seeing the world, the following snippet is very similar.

Update 1:
there is actually a function in Kotlin for this.
And it’s the filterIsInstance<T>() method.

And the greatest thing about it was that I got a response in the Kotlin slack channel 5 minutes after my post! That’s great support!

And how I realised this was when using Rx, so the same goes there.

Update 2:
there is actually an operator in Rx for this as well.
It’s the ofType() operator.

So in conclusion, I have no problem (edited)

But when I needed this solution I actually managed to solve my Rx problem (which I thought was still a problem) in an alternative way. This was really fun and the ground structure of the solution might come in handy for other problems I run into. Here is the “hack” if you will, an extension function in Kotlin that combines filter and map.

This is a neat little solution that works wonderful. It can come in handy when making domain driven designs. Or when a combination of operations can be given a more descriptive name and grouped.

The link to the ofType operator in Rx:

The link to the filterIsInstance function in Kotlin:

→ Bob

Lead Developer at Qvik, Coach, Agile Thinker, GDG Lead.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store