In car2go we started using Kotlin in production around the time when Google confirmed it as an official language for Android. That is an awesome language and I enjoy all little things which it brings. And, oh boy, it brings a lot of those.

Of course, most of those features are mentioned in the documentation but, even then, once in a while someone from the team rediscovers yet another nice trick which you can do with the language. I would like to share with you our “discoveries”.

with() and apply()

with() allows you to pass a function as a parameter in which you can call members of an instance as if you were writing code within a class of this instance. Basically, instead of having this:

You can have that:

Not a game changer, but looks better in my opinion. Going further, if textView is nullable we can use apply() instead:

Streaming-like operations for single values

By this point probably everyone knows about streaming operations for collections. That stuff:

There is however a way to perform similar operations on a single value. In car2go we have a RecyclerView adapter which at some point tells us how many list items we should display for given parking spot. The Java-way looked pretty much like that:

That isn’t exactly bad. But I believe we can improve it. With takeUnless() , let() and elvis operator we can do magic like that:

This version takes more lines and might be not as clear as Java version at the first glance but as soon as you’ll get used to the API and understand the contract of each method the code will become more readable and intuitive than the Java-way.

What I like the most about this approach is that you have clear expectation that neither takeUnless nor let will change any variables outside of their scope. Unlike with if clause where pretty much anything can happen and you have to take a special care when reading through such code.

Overloaded operators for collections

Aren’t they awesome? Yet somehow I missed this feature initially.

Now let’s compare it to the Java-way. Because comparison is fun.

With that said, you can also overload operators yourself and do all sorts of crazy stuff with it… which no one else will probably understand, so please don’t.

Defining a map

From time to time, there is a need to define some hardcoded Map . There are several ways to do them in Java. That would be the most straightforward one:

Doesn’t look too bad with 3 values and simple String entries. However as the code grows it gets harder and harder to read. Luckily there is a Kotlin way to do the same thing, which I find a bit better.