Five reasons why you should use Scala on Android

Last week I've introduced the basic building blocks of a Scala Android App and talked only very short about the motivation. This time I will give you five catchy reasons why you should not go mainstream and use plain old boring Java but give Scala a favour on Android.

1. Escape the callback hell with Future's

On Android you have to spin off a thread for everything that needs some time until it's finished. You can't do this on the main thread, because then you would block the responsiveness of your app. This work could be e.g. a call to a REST server to fetch or post some data.
AsyncTask from the Android library helps Android Java developers with this problem. But it uses callbacks as soon as the task completes. This doesn't sound so bad if you only do one thing, but just think about dependent async calls: First fetch user data, then fetch the avatar whose link has been contained in the returned user data. Now you have to nest callback handlers which really leads to ugly code. If you're not convinced read "Callbacks are the modern gotos".

Fortunately functional languages like Scala have a very nice solution for this problem and they are called Monad's. In our concrete case of async execution the Monad to use is Future. You just have to return a Future of your return type instead of returning it directly. The nice thing is now that you can combine Future's very easily using a for comprehension:
With that mechanism you may combine several inter dependent async calls and they nearly look as simple as synchronous code.

2. Use concise functions instead of verbose anonymous listener classes

Android's UI code makes heavy use of the Listener concept like several other Java based UI frameworks like Swing. Every java developer knows the extreme amount of boilerplate code that is needed to write an anonymous listener class:
(Yes I know, this is already Scala, but it still uses the standard android listener)

You may now simply define a function that wraps the ugly listener concept or simply use Scaloid which already supplies you with one:
If you prefer not to use Scaloid you just have to use the "Pimp my library" Pattern of Scala and enrich every Android View with a method that accepts an "on click" handler function:
Now you simply import the implicit class and you may use e.g. button.onClick() like shown above.

3. Concise Scala code vs verbose Java boilerplate

Java is still ultra verbose and you as a developer need powerful IDE's to generate hundreds of boring code lines like this:
In Scala the above is simply done with:
Case classes generate everything for you: equals, hashCode, getter's, toString. No setter's since Scala case classes teach you to favour immutability. But Case class have clever copy methods if you need to create an altered version of an object.

4. Use compile time checked dependency injection with the cake pattern

You don't need Spring's Dependency Injection facilities or Guice with Scala. You'll have something more powerful without the need to use an external library. Just learn and use the Cake pattern and you are able to use Dependency injection in your Android code. And the best: It's statically checked by the compiler and not at runtime like in Spring or Guice.

5. Get rid of if-cascades with Pattern matching

Checking conditions of an object in Java often leads to several if-cascades. And if you also want to extract some data out of the object you'll have to write a lot of code. Scala has it's swiss army knife for that: Pattern Matching. Here's an example:

With pattern matching you have the possibility to decompose an object into it's parts.
Case classes already provide automatic support for pattern matching, but you may use pattern matching even for java classes or classes for which you don't have the source code by using Scala's extractor's.


Scala on Android: Motivation, Building and useful libraries

Today I'll start a Scala on Android blog series.

This knowledge is mainly taken from the research and the work I've done for my current project. At the beginning there were big discussions if we should do plain old Java or use Scala for the app. Fortunately we decided together to go down the Scala road. See this Interview for more insight on the decision (not very technical and in german)

Here's the upcoming (it's Beta at the time of this writing) Play Store listing for the App.
We develop this app with Scala 2.11 for Android 4.0.3 and above.

Main Motivation

Scala is a beautiful language. I come from Java land, and it was a real eye opener to work with Scala and learn day by day more of the beauty of functional programming. So I definitely wanted to write as much Scala code and as less Java code as possible, even on Android.

But there's one really convincing feature in Scala that makes your life on Android so much easier and less painful: Futures instead of AsyncTask's Callback Handler approach.

With callback handler's you'll get soon in a spaghetti code situation. If you use Scala Future's you may easily combine them with their combinators, for-comprehensions or the new async/await macros. Just write some code with both concepts and you will see the difference.

For a more detailed  view on the motivation, see my follow up post.

I'll now start with the basic building blocks of the App.

Build system

One of the biggest questions when you start is: "Which build system should I use?" As I'm not a big fan of SBT I tried to look around and found one for my favourite build system gradle: gradle-android-scala-plugin. But unfortunately the author doesn't recommend it to use it in production yet.

So I tried out the Android SDK Plugin for SBT and it turned out to be very well. It is actively developed, the author is very responsive and helpful, and the Intellij integration via the SBT-Idea plugin is working well enough.

Scala and the Dexer limit

Compiled Java code for android is not shipped as .class files but in a format called dex. The problem is that currently one dex file allows only 65k method entries, and there are some big java android apps out there that already hit this limit. (e.g. the facebook app).

So even if you have a normal sized app, if you write it in Scala the scala library itself will reach this limit. But every Android developer knows ProGuard: A tool which inspects java bytecode and removes unused code and optionally obfuscates it. 

So if you use Scala for your app, using ProGuard is mandatory, even in the development stage, because it strips away a lot of the unused methods and fields from the Scala library.
These tools are very well integrated in the Android SDK Plugin for SBT, where you also have the possibility to customize a Proguard cache to save a lot of time during your development build cycles.



REST client 

As a rest client we use the Spring Android REST Template from Spring Android. Not much to say here, it just works well. (In my Java days I was a big Spring fan.) We don't use the standard spring json parsing message converters. See next chapter.

Json Parsing

For my own (and first) Android app in Java I had used GSon for Json Parsing. It's very small and easy to use but unfortunately (and not surprisingly) it does not well support the Scala types we all love to use: Options, Lists etc.
So my next evaluation was to use Jackson together with the Jackson Scala Module. At Gutefrage.net we use it on the Scala server side, but it showed up that it is very cumbersome to use on Android. The main reason is that it heavily relies on reflection and if you look at how Proguard works, you'll get a feeling why this will cause trouble. You'll have to add several "-keep" rules to tell Proguard not to remove code that Jackson needs later on to build up your object graph from json, and a lot of more stuff. I would not recommend it.
So the final library in my journey was spray-json. It is a native Scala library and you define your json mapping as an external protocol (in Scala).

This has several advantages:
  • No annotation and no reflection magic, all compile time, so no need to configure Proguard in any special way
    Type-class based (de)serialization of custom objects (no reflection, no intrusion)
  • Annotations (e.g. used in Jackson) allow one representation, external protocol allows multiple
  • Define a protocol for classes w/o source
  • Simple and lightweight (Jar Size compared to Jackson)
  • Plugging in of fast low level parsers simple
As it turned out the standard json parser of spray-json isn't the fastest, but it's very easy to plug in a really fast one. We use Jawn.

Libraries for making Android less painful

We use Scaloid, it has several nice features e.g.
  • turning the usual android callback handlers (e.g. onClickListener) into a functional equivalent
  • a Scala DSL for building and reusing layouts
  • a lot of Rich* classes for the Android functionality and implicit parameters reducing a lot of boilerplate code 
  • and a lot more
At some early point of the app we decided however not to use the Scala DSL as an alternative for the android layout xml's, but Scaloid allows you to make your choice.

Another UI DSL Library which might be worth to have a look at is Macroid.

The next upcoming post will talk about generalizing the error handling while talking to API servers.