Random thoughts about analytics, business technology, and other musings.

YouTube Videos

A Simple Neural Network

KotlinConf 2018 - Mathematical Modeling

Creating a Sudoku Solver from Scratch

Traveling Salesman Problem

Text Categorization w/ Naive Bayes

Monty Hall Problem

Solving World's Hardest Sudoku

!doctype>

Thursday, February 4, 2016

Kotlin + RxJava = Functional Powerhouse

As a software developer working in a tactical business environment, I'm always looking for ways to do more with less code. Even better, if I can modify and scale code to constantly adapt to business demands then I have to do less code re-writes.

Java has been my go-to language as it is practical, scalable, performant, portable, and statically-typed. As I became proficient and took on more ambitious projects, it started to feel cumbersome (and I kept eyeing C# wishfully). Thankfully I found RxJava last year, and reactive programming enabled me to take on tasks that I would hesitate to do before.

Utilizing RxJava almost exclusively for all my projects, I became much more productive and the quality of my applications increased. But I slowly started to realize the limitations of the Java language were holding RxJava back. Even with Java 8's lambdas, some functional programming tasks became very verbose.

For instance, using the compose() operator which accepts a custom Transformer allows you to create your own operator with existing RxJava operators. The problem is it can quickly become wordy and less fluid.

Here is a simple example. I can create a custom Transformer that turns an Observable<T> into an Observable<ImmutableList<T>> since I like Google Guava's immutable collections.

Even worse if I start to create more complicated Transformers or Operators with arguments, my compose() statement can start to get pretty ugly. If I wanted to collect items into an ImmutableListMultimap, it starts to get less fluid with the lambda arguments.

These may be trivial examples, but for larger applications these problems can quickly become amplified. Precious code real estate becomes eaten away even with the efficiencies of RxJava and Java 8 lambdas, and we have not even gotten to the subject of Tuples and data classes! But Kotlin solves all of these problems and more.

Introducing Kotlin

I tried looking at Scala, Python, and other languages. I especially looked at Scala but despite all the praise it gets, I found it too esoteric. Then one day I found JetBrains sharing their new language called Kotlin. They advertised it as an industry-grade, business-focused language emphasizing practicality rather than convention. JetBrains, the creator of the popular Java IDE Intellij IDEA, built it because they felt they could be more productive using a language that Java should have been. After studying Kotlin and re-writing two home projects with it, I quickly became sold and am ready to use it exclusively. The fact it is 100% interoperable with Java and all Java libraries made it a quick sell as well.

But in this post, what I really want to share is my experience using RxJava with Kotlin. Ironically, I found RxJava works better with Kotlin than Java itself. It just expresses functional programming concepts so much better.

For instance, I can "add" methods to the Observable using extension methods, without even extending the class! This is nothing new if you came from a C# background, but this was always the #1 thing I wished Java would have. Below I add toImmutableList() and toImmutableListMultimap() methods to the Observable (in Kotlin methods are actually called functions). I can then call those methods directly on the Observable rather than creating a compose() statement.

We did not have to wrap these functions inside a class. Unlike Java, Kotlin does not force you to put static methods in a class. This is really helpful and helps eliminate a lot of boilerplate, especially for procedural programs.

The type of the source variable is inferred, allowing us to not have to explicitly declare it as an Observable<String>. You can do that if you want to as shown below. In Kotlin the type comes after the variable name (separated by a colon :). This is done because the variable name is likely more pertinent to you than the type, so it is declared first to making finding it easy.

You can express lambdas much more easily. Instead of having to write out a lambda for a simple one-to-one mapping like s -> s.length(), you can express this with a much more succint it.length, where it refers to the single incoming item emitted (this is featured in other JVM languages). Also, there are no paranthesis () to receive functional arguments. Instead you use curley braces {} and express the entire function for that operator in it. This is especially helpful because you can put multiple lines in the curly braces { } at any time.

source.toImmutableListMultimap { it.length }.subscribe{ println(it)}

You can "add" functions/methods to a class without actually extending a class using extension functions. This single statement below adds a toImmutableList() function to the Observable everywhere in your application (unless you make it private or alter its scope). How is this done? The compiler simply makes it a static method when turned into bytecode, but you get the nice syntactic sugar as well as seeing it in your auto-complete. You do not have to target generic types either with extension methods. For example, I could make a concatStr() extension method specifically targeting Observable<String> and not Observable<T>.

Data Classes

Another great feature of Kotlin is data classes. Have you ever wanted to simply zip two values together, but had to create an entire class just to pair them up with hashCode(), equals(), and toString() implemented?

It is not fun I had to write 36 lines of code just to create a CodePair class holding two properties. This problem comes up in functional programming quite a bit, and the only alternative is creating esoteric tuples which only obfuscate the code.

But in Kotlin, you can declare something called a data class. This allows you to quickly declare a class in one line with all its properties, and it will take care of the hashCode(), equals(), toString() and even clone/modify builders for you.

We declared a CodePair class right inside the main() function, and it only exists in the scope of the main() function. It has named properties letter and number you can access. This opens up a lot of tactical possibilities that were borderline impractical to do in Java. Being able to declare simple classes on the fly and have the common method implementations done allows fast, organized, and legible code to be developed quickly.

Conclusions

I have only scratched the surface in sharing what Kotlin can do, with or without RxJava. This was not a tutorial but just a quick showcase of how RxJava expresses differently in Kotlin. I hope I have effectively shared my experience and you are curious to check out Kotlin. I know Scala can do quite a bit with RxScala, but Kotlin is different. It really serves folks who need the tactical abilities and simplicity of Python with the scalability and power of Java. When you throw RxJava into the mix with Kotlin, I have found it to be a very rewarding combination. Did I forget to mention that there are no primitives or boxed types either? There are so many features in Kotlin that would be out of scope to post here, like nullable types

As a sidenote, Kotlin is supported on Android. You can also checkout the RxKotlin library which extends RxJava to take advantage of Kotlin functionalities (such as adding toObservable() methods to collections).

6 comments:

This concise code comes at a huge cost. Only you know what it does and it is hideously ugly. That bunch of single letter variables, scattered through a field of dashes, arrows and commas is absolutely impossible to understand, if you aren't the one who wrote this write-only code. No explanatory variables, no intent through naming, a huge amount of mental mapping is needed in order to comprehend what the idea of that code is. It would be a pain to work with such a code base. I hope this doesn't catch on. I want to work with readable, self-explanatory, clean code. Not the less-characters-possible code

Variable naming is on the hand of the programmer, Java/Kotlin does not interfere with them.I guess the 'mental mapping' you mentioned is partly because of the noise of Rx & Guava usage.I'd suggest having a look at Kotlin itself on its own (if you haven't heard of that). It opens up many possibilities.This article is rather a non beginner as a Kotlin intro though.

Thanks Hoang, you are correct. This article was written for an audience already familiar with RxJava and functional programming, and show how Kotlin can solve some problems they likely have encountered. It id by no means an introduction to Kotlin or functional programming. JetBrains has some great online documentation for Java devs to learn Kotlin in a few hours at kotlinlang.org

Java exceptions provide a way to process synchronous errors such as divisions by zero and out-of-range array indexes, and this article offers top practical guidelines on their use. The article includes when to use Exceptions, when you neither catch nor throw exceptions and (importantly) when to use standard Java exceptions. See more assignment help programming