We use cookies on our website, hope you don’t mind. Just imagine a plate of delicious meringues, they look like clouds. Read more

Development

Why Kotlin Is the Hero Android Needs

Share this Article on:

Stay in touch. Subscribe to our Newsletter

On May 17th Google announced Kotlin as the officially supported language for Android. It was no surprise for us at 10Clouds. It’s been the most important shift in Android development since many ditched the generally hated Eclipse for Android Studio, based on IntelliJ, a beloved IDE among Java Developers.

Let’s face it – Java is old. A breath of fresh air was all we were waiting for. Since February 2016, when Kotlin 1.0 shipped, we at 10Clouds kept a close eye on its development.

It’s easy to start with Kotlin

To paraphrase the famous author John Green, I fell in love in Kotlin the way you fall asleep: slowly, then all at once. I started learning Kotlin with Kotlin Koans. It’s a series of unit tests that require making them pass. It took some time for a Java head like me to get a grasp of the new concepts, but eventually, all pieces clicked into right places.

Everything was new and, at the same time, familiar. When I didn’t know how to write something in Kotlin, I would write code in Java. Then I’d use a Java to Kotlin converter shipped alongside the Kotlin plugin. It was a huge help. After a few hours, I was so confident in my skills in Kotlin that I didn’t want to go back to Java ever again.

Kotlin makes writing Android apps fun again

Why Kotlin Is the Hero Android Needs

As JetBrains likes to say, Kotlin is a language created from industry to industry. They understand problems that modern software developers run into and offer great solutions to help us deliver reliable software in a much quicker and enjoyable way. Writing apps in Java has always been connected with generating loads of boilerplate code. Remember POJOs? With the introduction of Kotlin’s data classes, we can say goodbye to generating the getters and setters for all object fields and writing implementations of toString(), hashCode() and equals() methods. Instead of 50+ LOC in Java, we can reduce that number to 1 (!) in Kotlin.

/**
* Example data class in Java
*/

public class Station {

   private String id;
   private String address;
   private String city;
   private double latitude;
   private double longitude;

   public String getId() {
       return id;
   }

   public void setId(String id) {
       this.id = id;
   }

   public String getAddress() {
       return address;
   }

   public void setAddress(String address) {
       this.address = address;
   }

   /**
    * And many more getters and setters
    */
}

 

/**
* Example of a data class in Kotlin 
*/
data class Station(val id: String, val address: String, val city: String, val latitude: Double, val longitude: Double)

Remember filtering lists with for loops? Thanks to the functional approach to collections, we can also reduce all the complex, multiline instructions to only one line of code.

/**
* How collections were handled in Java
*/
void processList(List<Integer> list) {
   List<String> stringList = new ArrayList<>();
   for (Integer i : list) {
       if (i % 2 == 0) {
           stringList.add(i.toString());
       }
   }
}
/**
    * How Kotlin handles collections
    */
   fun processList(list: List<Int>) {
       val stringList = list.filter { it % 2 == 0 }. map { it.toString() }
   }
}

Remember Singletons? Even this mighty design pattern gets taken care of in Kotlin thanks to object declarations.

/**
* Object declarations make singletons even simpler
*/
object Injector {
   var component: ApplicationComponent? = null
   fun start(application: Application) {
       component = DaggerApplicationComponent.builder().androidModule(AndroidModule(application)).appModule(AppModule()).build()
   }
}

Creating layouts programmatically in Java could result in a mess. Thanks to type-safe Builders, we got one of the most interesting libraries in Kotlin: Anko Layouts, which makes building layouts from code less complicated. Builders are also great for generating HTML files as well as many other DSLs.

Java can be a struggle. There’s no pattern matching, typealiases, extension functions. We had to overload many methods because we couldn’t declare default parameter values and so on, and so on. With Kotlin, most of these problems are gone. All its simplistic, syntactic goodness comes together, creating a new enjoyable experience for developing Android apps.

Kotlin helps create more reliable apps

Every app ever written in Java struggled with the dreaded NullPointerException (infamously called as the billion dollar bug). It interferes with the user experience, often driving her/him to uninstall the app and never use it again. With Kotlin and its introduction of nullable types, it (almost) eliminates the danger of null references in the code. From now on, the compiler plays the role of a guardian and all possible threats of NPE are treated as compile time errors.

var component: ApplicationComponent? = null

fun doSth() {
   // When component is null do the right side of Elvis operator
   component?.getApiRequests() ?: doSthElse()
}

You can use Kotlin solutions within your old Java codebase and vice versa

Why Kotlin Is the Hero Android Needs

Introducing Kotlin to an existing Java codebase costs almost nothing. Do you want to call Java code from Kotlin class? No problem. Oh, the other way around? Easy.

Behind the scenes, Kotlin is compiled to Java 6 bytecode. You don’t have to worry that you are adding something incompatible to the existing codebase. We introduced Kotlin to many of our projects that were Java-only and it worked seamlessly. We started very simple, converted our POJO classes to Kotlin. Then we added some logic, wrote couple of extension functions (getting rid of Decorator pattern in the process). Finally, we removed bloated Retrolambda library. At first we encountered some problems with Kotlin annotation processor. It only took some tweaking with Gradle build files to make our project work again.

Kotlin works well with both most popular architectures: MVP (thanks to Kotlin Android extensions) and MVVM. But, this subject is so vast that we will cover it in future blog posts.

It has Jetbrains seal of quality

Why Kotlin Is the Hero Android Needs

We all trust JetBrains with providing us tools that we use on a daily basis. IntelliJ, Android Studio, PyCharm, and AppCode are just a couple of the most popular IDEs used by developers all around the world. These products are the reason why JetBrains earned trust within developers community.

Speaking of which, the Kotlin community is open and helpful to newcomers. I spent a couple of months on Kotlin Slack and learned a lot about language itself as well as the future plans JetBrains holds.

Becoming a first-class language on Android: What this means for developers

I am almost sure that the applause after the Kotlin announcement on IO 2017 was the loudest during the entire evening. Kotlin will be now shipped with Android Studio working out of the box, starting with version 3.0. No extra installations needed. No more incompatible plugins. All thanks to close collaboration between JetBrains and Google.

For developers, it’s a chance to use this fresh yet mature language to reduce problems associated with rusty Java. The elegant syntax will for sure attract more developers to write apps for Android platform. So did Swift introduction for iOS.

What the future holds for Kotlin, Android, and other platforms

As Kotlin became a first-class citizen in the Android world, it still aims to be a reliable multiplatform programming language. With Kotlin, you can develop server applications with Spring, KTOR, and many more JVM back-end frameworks. With the release of version 1.1 came JavaScript support. One of the missing pieces are iOS and MacOS, but if you paid close attention to Kotlin’s Twitter account, there was successful proof of concept for a project called Kotlin Native.

Is Kotlin a production-ready language? Definitely. We used it in our projects and never looked back. With such an amazing community, great effort from JetBrains and support by Google, there is almost no excuse for not trying it out yourself. Without further ado, let’s get back to work!



Need a Kotlin developer? Get in touch with 10Clouds, we’d love to work together!

by Piotr Kaźmierczak, Android Developer
  • Inam

    *laughs in Java 9*

    • Kapral Klitorchuk

      He who laughs last, laughs longest

    • Margaret Leber

      *laughs at Java 9*

    • Piotrek Kaźmierczak

      My bet is: android devs will get Java 9 in 2020 or later (probably later), since Google took its sweet time with introduction of Java 8 before

  • Margaret Leber

    Would have been nice if they’d gone with Scala, but Intellij had a leg up by “donating” Android Studio.
    Scala Native is ‘way beyond “proof of concept”, at this point.

    It’s probably a good move…certainly better than nothing.

    • Piotr Potulski

      Scala has also some disadvantages – ex. build time. I’m using Kotlin for three years for Android development. So – official support changes nothing for me (ok, maybe it will be easier to convince some conservative CTO). The fun thing is that it’s also possible to use Scala for Android development (as far as I know).

    • Piotrek Kaźmierczak

      Thank you for your comment 🙂
      As someone on Kotlin Slack said: Kotlin is Scala for people who hated Scala. I tried writing apps using it in the past and all I can remember is that its learning curve was way steeper than Kotlin

  • Charlie

    The drawback that I see in choosing Java 6 bytecode is that many security features of the OS and hardware are unavailable.

    Within the JRE, chroot() is not available, and an app can’t fork off a child that runs setuid() to set up a privilege separation jail. AES encryption sessions must trust the JRE to use any available cpu op-codes that render AES safe. System calls in general aren’t available.

    Android should have extended the Dalvik/ART environment by adding specific collections of system calls for security. Features such as become_nobody(), jail(), or even OpenBSD’s recent pledge() would be great improvements.

    As I work mostly as a DBA, I constantly wield sshd/stunnel and other chroot()-capable applications when I don’t know or trust the other side of my connection. This should be available in the world of Java bytecode. I’m beginning to realize Kotlin’s great innovations in the language syntax and capability, but the target bytecode needs some features.

  • Jacob

    Kotlin is not primary. It is supported officially but not primary. Check facts and don’t clickbait.

    • dude

      It’s well on its way to be primary within a year. Deal with it.

    • Dave

      there’s not a single word in this post that suggest Kotlin is primary language for Android

  • prestonjb

    That’s all well and good but when business logic needs to be shared across platforms (data class myRecord ( etc) will there be kotlin for Windows and Linux to code share as Java/c++ can?

    No I know I could write in Java.. what I’m asking is if a lib is written in kotlin and I need to edit or use it on windows-java…

    (Was also one of my complaints about Android studio is though as bad as eclipse is.. we could build cross platform in the same ide)

you may also like these posts

The Best Software Developer Conferences in 2017 in Europe

How to Switch to Vim Without Ruining Your Workflow

Behaviours in Xcode: the Ultimate Guide for iOS Developers

SUBSCRIBE TO OUR NEWSLETTER

Get the latest info about technology, design, product management (and some snaps from 10Clouds life) - subscribe to our newsletter.