Why migrate your Android app to Kotlin?

Why bother making the effort? Kotlin is an amazing language that has a ton of benefits for fast, easy, Android development. It’s quickly becoming the preferred Android development language. In this article we will discuss the pros and cons of migrating to Kotlin, and point out some next steps to make your transition super easy.

Benefit 1: First Class Android Support + Android moving away from Java

Android is actively promoting developing in Kotlin. All of Google’s samples are in Kotlin, with a Java equivalent option for some examples. Many of the new Android libraries are being written in Kotlin ,  for Kotlin, such as the Android 9 libraries, AndroidX libraries, and the Android KTX library. Android Studio itself has first-class support for the language — meaning Kotlin support is built in with the IDE.

Unfortunately for Java-only developers, continued Android first-class support for Java is no longer guaranteed. Due to the recent Oracle vs. Google lawsuit about Android’s use of Java, Google has announced that they will drop support for the Android Java APIs and will instead use the open source OpenJDK. Most likely, Java will continue to stick around for previous app version support, but if you want to stay current, learning Kotlin will keep you in the game with the latest and greatest Android libraries and techniques!

Furthermore, Android Studio provides many helpful tools to help you learn and work with Kotlin, so it’s easy to pick up the new language as you develop. The IDE even has a tool to automatically convert your Java code into Kotlin! The IDE includes inline code suggestions on how to make your Kotlin code perform better, and will pop up helpful tips as you develop. This is very helpful!

Android Studio Automatic Kotlin Conversion

Benefit 2: Compatible with Java code = Smooth Step by Step Migration Possible

When used with Android, Kotlin decompiles into Java-compatible byte code—you can run Kotlin code from Java code and vice-versa. This allows you to piece-meal convert parts of your app or library instead of having to do the entire conversion in one giant refactor. If doing a large migration seems too daunting a task, a phased migration is an excellent option — you can make headway on Kotlin migration, but do so in a slower, more protected approach.

Benefit 3: Null safety with Kotlin + Build better APIs

Are you tired of those pesky if-null checks? Tired of getting runtime null pointer exceptions? Unlike Java, Kotlin enforces null safety. So, if you’ve specified an API or value as non-null, Kotlin enforce that non-null. Unlike Java — you can count on your arguments coming through as specified. Think of all the time you could save on null checks with more robust APIs!

val size is set to default 0; add does nothing here.

If you’re dealing with a null in code, Kotlin allows you to use safe call operator ? to run methods/access attributes on a nullable value. Methods being run on a null object won’t execute, and attributes from a null objects will return null. Want to provide a default value instead of null? No problem! Just use Kotlin’s operator ?: to provide a default value if object is null. Cool, huh?

let is like an if not null check; apply allows changes to the object.

Still not satisfied? Want more time-savers? Kotlin also includes helper methods like let and apply to allow developers to use and make changes to objects without having to worry about re-referencing objects or nullability issues. Now that you’re dealing with nulls in a more null-safe manner, say goodbye to all of those NullPtrException crashes!

Benefit 4: Named Constructors w/ Default values

Want to write a class constructor, but don’t want to have to remember the order of your parameters? Kotlin’s classes have named variable constructors, which means you can specify the name you’ve given to the variable, and can thus create a constructor with parameters provided in any order. You can also provide default values in case you don’t want to have to specify each value.

Example of named constructors use and default parameters

Benefit 5: Write faster code!

Be a super star, write faster code! According to the Kotlin website,  a class written in Kotlin uses 40% less code than a class written in Java on average. Kotlin has faster replacements for many of the main Java staples like the for loop, map, and filter with its own helper methods such as forEach, forEachIndexed, map, and filter. Creating basic data structures is made fast and easy with arrayListOf and hashMapOf. Kotlin even has a helper method firstOrNull where you can give it a filter and it will automatically find an item for you! Awesome! These methods help take out much of the boiler-plate code we have to write and will improve your velocity!

forEach and forEachIndexed can completely replace the for loop

map can apply changes to each item in the list; filter can filter the list, and firstOrNull searches the list for you

Benefit 6: Lambdas to the rescue!

Java 8 now includes the ability to pass single or double argument functions into a method parameter or change certain listeners into lambdas, but Kotlin takes this concept to a whole new level! You are no longer limited to single or double argument lambdas, you can pass whatever lambda you’d like. Kotlin even static checks the types of the arguments of its lambdas for you. Kotlin also provides the ability to create closures on the fly, which makes it much easier to include a small set of logic for callbacks and click listeners, inline. All of this makes life much easier when it comes to callbacks, exceptions, and listeners.

Example of passing lambdas as parameters

Benefit 7: Swift Crossover

Ever been curious on what it’s like to develop in Swift? Kotlin is here to help! Kotlin and Swift are very similar in language syntax. Both include optionals in their syntax for null safety and both handle lambdas in a similar fashion. On the bright side for Android developers, Kotlin is not as strict as Swift with unwrapping null checks, so development in Kotlin is easier and more dev-friendly than developing in Swift. If you want to make your code easier to read and pick up when switching between platforms, Kotlin is for you!

Benefit 8: Fun new libraries

Many new libraries are being written for Kotlin, including the Kotlin Extensions library, which includes helper methods such as the synthesized findViewById where you can avoid having to create View variables and just use the layout-id-synthesized value.

No findViewById required to get layout views

If you’re concerned about style/lint errors, there’s a ktlint gradle tool you can easily integrate into your code to catch and fix those errors. There’s also the MockitoKotlin library for those of you who like writing unit tests with Mockito but (like many) don’t enjoy writing those argument captors.

Argument captors and mocking are so much easier with MockitoKotlin!

There are very few cons to migrating to Kotlin, but let’s go ahead and address these minor issues.

Issue 1: Getting your team up to speed

Like learning any new language, picking up Kotlin will take some time. Before you start, it’s a good idea for your team to get some familiarity programming with Kotlin.  Fortunately, there are many Try-Kotlin courses you can use to learn the language. Once you have a handle of Kotlin’s syntax, the best way to learn to develop in Kotlin is to dive in and convert or write some small classes. I’ll include a strategy to migrate to Kotlin step by step and get your team up to speed at the same time in the next Kotlin migration article.

Issue 2: APIs with NonNull parameters are now enforced

With Kotlin, you can now enforce APIs on NonNull parameters. Kotlin will not compile if you specifically try to put a null into a non-null API and the IDE will also warn you of the mistake. However, keep in mind when re-writing APIs that: if you have a runtime null going into a non-null API, Kotlin will force a crash with a null argument exception. This is not a big deal if you are diligent in rewriting your APIs and communicating any changes to your team.

Issue 3: Generics

If you have lots of generics in use in your Java code, Kotlin typing with Generics can sometimes be more difficult. Kotlin will work with generics at runtime, but may not statically verify your typecast of a generic at compile time, so Android Studio will show a warning. Also be aware that Java and Kotlin use generics in different ways. If your APIs include uses of generics and those APIs are used in Java classes, you may need to do some extra work around those APIs when you migrate them to Kotlin. When I work with generics in Kotlin, I try to make sure to use strong typing, extending my generics from a base type instead of using a star operator.

Issue 4: Checking git changes after a migration

One occasional headache that teams can run into when migrating to Kotlin is code reviewing converted files. This is not a big deal, when you’re done with your changes, just take these few extra steps to clean your commits and it will be easier to code review your file.

When you convert a class to Kotlin, you are renaming the file with .kt extension, so when you first view it in git, it can look like you removed the .java file, and created a new .kt file. This can make it difficult to tell what you actually changed.

Fortunately, there’s an easy fix for this, when you’re done with your migration:

  1. Create a new branch, switch to the new branch.
  2. Rename the files you’ve converted to Kotlin in the original branch to have a .kt extension instead of the .java extension. Commit.
  3. Reset those files back to the .java extension and commit again.
  4. Cherry-pick the changes from your migration branch over to your new branch. You will now have the .kt rename commit, the .java reset commit, and your cherry-picked changes on your new branch.
  5. Rebase your new branch, squashing the .java commit with the cherry picked changes
  6. DONE! Now your git commit history will show just the changes within the Kotlin file, which is much easier to read.

As you can see, there are plenty of benefits and advantages of converting to Kotlin. On the whole, migrating to Kotlin is a process that has great benefits to your team’s velocity, your code’s health, and your app’s performance. In the next article, we will discuss how to be an advocate for your team’s migration to Kotlin, proposing a phased migration approach that should help mitigate bugs and increase your team’s strength in Kotlin. See you soon!

The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.