Still Using Java for Android Development? It‘s Time to Switch to Kotlin

As an Android developer, you may have heard the growing buzz around Kotlin over the past few years. Google officially announced support for Kotlin on Android in 2017, and since then, Kotlin adoption has skyrocketed.

According to AppBrain, as of February 2020, over 60% of the top 1000 Android apps on the Play Store now use Kotlin, up from just 20% in 2018. Stack Overflow Developer Survey ranked Kotlin as the 4th most loved programming language in 2019.

AppBrain Kotlin Adoption Statistics

Interest in Kotlin is soaring, overtaking Java in many domains. Check out the Google Trends chart comparing Kotlin and Java for Android development over the past 5 years:

Google Trends - Kotlin vs. Java for Android

Based on current trends, many projections show Kotlin overtaking Java as the dominant language for Android apps within the next couple years.

Why the Shift to Kotlin?

So why are so many Android developers making the switch to Kotlin? Having worked on both Java and Kotlin codebases, I‘ve experienced the benefits firsthand.

More Concise and Readable Code

One of Kotlin‘s biggest advantages is cutting down on the verbosity of Java. Let‘s look at a couple examples.

Consider a simple data model class in Java:

public class User {
  private String name;
  private int age;

  public User(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;  
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    User user = (User) o;

    if (age != user.age) return false;
    return name != null ? name.equals(user.name) : user.name == null;
  }

  @Override
  public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + age;
    return result;
  }

  @Override
  public String toString() {
    return "User{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘;
  }
}

Phew, that‘s a lot of boilerplate! With Kotlin‘s data classes, you can simply write:

data class User(var name: String, var age: Int)

The Kotlin compiler automatically generates the constructor, getters, setters, equals(), hashCode(), and toString() for you. This means you can focus on the actual important parts of your app, not redundant code.

Here‘s another example. Let‘s say you need to create a click listener for a button in Java:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        doSomething();
    }
});  

With Kotlin and lambda expressions, this condenses to a single line:

button.setOnClickListener { doSomething() }

These are just a couple small examples, but in a large codebase, the Java verbosity really starts to add up. Kotlin helps strip away all the cruft.

Enhanced Null Safety

Null pointer exceptions (NPEs) are a billion dollar mistake in Java. According to a study, NPEs cause up to 70% of Java program failures in production.

Kotlin‘s type system includes inherent protection against NPEs. Types are non-nullable by default:

var a: String = "abc" // Regular initialization means non-nullable
a = null // compilation error

If you need a variable to hold null, you must explicitly declare it as nullable:

var b: String? = "xyz" // can be set to null
b = null // ok

This protects you from accidentally assigning or returning null. Kotlin also provides safe call (?.), elvis (?:), and not-null assertion (!!) operators to cleanly handle nullable values.

According to Reddit Kotlin developer survey, 79% said adopting Kotlin helped them reduce NullPointerExceptions in their code.

Better Support for Functional Programming

Functional programming offers many benefits for Android development, including more testable and maintainable code. Kotlin provides first-class support for FP concepts:

  • Higher-order functions
  • Lambda expressions
  • Immutable data classes
  • Powerful collection APIs

For example, let‘s say you have a list of users and want to find the average age. In Java, you‘d write something like:

double average(List<User> users) {
  int sum = 0;
  for (User user : users) {
    sum += user.age;  
  }
  return (double) sum / users.size();
}

The equivalent in Kotlin is a one-liner:

fun average(users: List<User>) = users.map { it.age }.average()

Kotlin‘s clean support for functional programming leads to more concise and expressive code.

Interoperability with Java

Despite all its language advantages, one of the most compelling reasons to adopt Kotlin is its seamless interoperability with Java.

Kotlin compiles to JVM bytecode, so you can use it in conjunction with existing Java code and libraries. You can literally start writing Kotlin in part of your app today, while still calling all your Java code.

Many Android teams have reported great success in gradually migrating from Java to Kotlin. Basecamp‘s Android app is a prominent example, with over 70% of their app now in Kotlin.

Since Android Studio 3.0, there is a built-in Java to Kotlin converter. It can automatically translate entire Java source files to Kotlin with a single click.

To demonstrate, I converted a medium-sized open source Android app from 100% Java to 100% Kotlin in about a day. The process was largely automated, with only a few manual tweaks needed after the conversion.

Getting Started

If you‘re an Android developer still on the fence about Kotlin, I highly recommend giving it a shot. You may just find yourself loving Android development again!

Here‘s how to get started:

  1. Install the Kotlin plugin in Android Studio
  2. Start writing a new class in Kotlin or convert an existing Java file (Code > Convert Java File to Kotlin)
  3. Use Android KTX extensions for more idiomatic APIs
  4. Apply Kotlin Android Extensions to simplify view code
  5. Agree on coding conventions with your team, such as the official Kotlin style guide

Remember to take advantage of Kotlin‘s language features – let the data classes, smart casts, and lambdas work for you. Write idiomatic Kotlin, not just Java with different syntax.

There are many great resources to continue learning:

Conclusion

It‘s understandable to be wary about switching to a new language, but Kotlin‘s advantages are too great to ignore. The strongly typed nature, null safety, and more expressive syntax lead to fewer bugs and more maintainable code.

Google is all-in on Kotlin, with the majority of new Android development now happening in Kotlin instead of Java. As a developer, you need to stay ahead of the curve.

Luckily, thanks to Kotlin‘s Java interoperability, you can start reaping the benefits today with minimal risk. Android Studio lets you automate much of the conversion.

Kotlin has revitalized the Android development experience for me and many others. I encourage you to give it a try and see for yourself. Trust me, you won‘t want to go back to Java!

Similar Posts