How to port existing Android applications from Java to Kotlin

//How to port existing Android applications from Java to Kotlin

How to port existing Android applications from Java to Kotlin by Najib Abdillah

If you’ve been developing Android apps with Java for years, you might wonder why you should care about Kotlin? The answer is simple: it’s the future of Android development.

In this article, we’ll look at Kotlin and why it’s such an important programming language for developers who want to create Android apps. You’ll learn some benefits of using Kotlin in your project and see how easy it can be for anyone with experience in Java to get started with developing for the Android platform using this new language. We’ll also follow a step-by-step guide that shows us how to convert an existing app from Java to Kotlin in order for you to successfully convert your codebase over.

This article aims to show you how to port existing code from Java to Kotlin while maintaining the existing code base and preserving its functionality. Before we dig deeper into the code, I assume that you are familiar with the basics of Android Development and Java. Moving your code into Kotlin is easy, especially if you are an Android developer who develops with Java.

If you are already up to speed with Kotlin and its benefits, we suggest jumping straight to Port your existing Java Android apps to Kotlin.

Table Of Contents

  • What is Kotlin ?
  • Why you should use Kotlin
  • What are the benefits of using Kotlin?
  • Port your existing Java android applications to Kotlin

Technical requirements

This article assumes you’ve already installed the most recent versions of Android Studio and Kotlin. The code files can be found here: https://github.com/Najibsaurus/CryptoWatcher

What is Kotlin?

Kotlin was created in 2010 by JetBrains. The first public release was in February 2016 and it’s now available as the default programming language for Android App Development.

In 2019, Google announced a new Kotlin-first approach for Android. This means that Kotlin will be used sustainably and is fully supported by Google for developers from various aspects such as tools, content, documentation, Codelabs, and Jetpack libraries. Google also recommends Kotlin as the primary language for developing Android apps.

Why you should use Kotlin?

Kotlin on Android has seen phenomenal growth in recent years. As a result, It has been gaining popularity with Android app developers. Moreover, Kotlin is also being adopted by the developer community at large. For instance, many apps have already moved to Kotlin.z`

Note

A Google report that says that more than 80% of 1000 apps are already using it and has been adopted by over 60% of professional Android developers around the world: https://developer.android.com/kotlin/build-better-apps

Kotlin has many benefits over Java including faster compilation times. It implies shorter time between code modifications made by developers while working on their apps.

What are the benefits of using Kotlin ?

By adopting Kotlin for Android development, you can receive the following benefits:

Fast Development Cycles

This is the main benefit of using Kotlin. The language offers concise syntax. It will make your development process efficient and thus, easy, and save a ton of time. In addition, your code readability through the use of cleaner syntax and less boilerplate.

Interoperability

Because Kotlin is completely interoperable with Java, you may use both at the same time without having to switch your entire codebase to Kotlin. Java code can call Kotlin code and vice versa. It will help to maintain two languages in your project and bring about increased productivity.

Code Safety

Mistakes are detected by the Kotlin compiler, which ensures that the code is safe. Kotlin has the ability to prevent possible errors such as NullPointerException. Google says that Android apps using Kotlin are 20% less likely to crash. : https://developer.android.com/kotlin/first

Mature Language

Kotlin is a simple and practical programming language. Kotlin offers a more expressive way to write code, which is in line with the principles of modern Java development. Kotlin can be used as an object-oriented programming language for building native mobile apps because it has type inference capabilities and functional features. It is also open source and free of charge. This makes it easier for developers not familiar with Java to use it more easily. It will reduce the chances of bugs in your application and It fully supports tools, libraries, compiler plugins, and Jetpack Compose.

Statically Typed

Kotlin’s type system is statically typed: once you declare a variable, it will never change its type in the entire scope of that declaration block. It will make your code more readable and reduce the number of lines of code to maintain or debug.

Now that we’ve understood what Kotlin is and seen some of the reasons for adopting it, let’s learn to port an existing Java based Android app to Kotlin.

Port your existing Java Android apps to Kotlin

If you want to take advantage of the full potential of Kotlin on Android, you will need to rewrite some parts or rewrite the application entirely from scratch. Since learning Kotlin from the basics takes time, it’s much easier to learn it in a task-oriented environment.

So, how do we port existing Java code to Kotlin? Let’s look at the steps next.

Preparing Android Studio

Before migrating an existing Java project into Kotlin, we’ll need to install the Kotlin plugin in Android Studio that lets you convert Java files.

Let’s make sure the plugin is enabled and installed in Android Studio.  Click File → Settings → Plugins → and type kotlin in search.

Figure 1 – Android Studio showing that Kotlin is installed

We will clone the Android project from this repository to clone the starter project. It has already been built with Java.

Clone the repository

Let’s begin!

  1. Open Android Studio and choose Get from Version Control.

Figure 2 – Android Studio start screen

  1. We are going to clone the starter project, paste https://github.com/Najibsaurus/CryptoWatcher.git in the URL text field and click Clone after that.

Figure 3 – Cloning the starter project in Android Studio

Note

Google added complete Kotlin support to Android Studio to assist developers in making the move from Java to Kotlin from Android Studio 4.0. I strongly advise you to use Android Studio 4.0 or above.

Build the project

Then, build and run the project.  Here’s what you’ll see:

Figure 4 – The app built from the starter code

The applications allow you to keep track of a cryptocurrency’s current price. Then, in 24 hours, disclose the detailed pricing. The project includes a Java code class, which is seen in the figure below.

Figure 5 – Java code class in the starter project code

Convert Into Kotlin

Now, we’re ready to get the code into Kotlin:

  1. One of the most important things is to convert the Gradle files from the Java code base. You could click the app directory and use the shortcut Ctrl+Alt+Shift+K or click Code → Convert Java File to Kotlin File from the top menu.

Figure 6 – Converting the Gradle file from Java to Kotlin

  1. Then, a confirmation dialog appears that states that the project will configure into Kotlin. Click OK, configure Kotlin in the project.

Figure 7 – Confirmation box for converting the Gradle file from Java to Kotlin

  1. Then choose the Kotlin compiler and runtime version, and click OK.

Figure 8 – Selecting the Kotlin compiler and runtime version

  1. Next, we need to convert the java file to kotlin in the same way. Click the package name directory folder then use the shortcut Ctrl+Alt+Shift+K or Code → Convert Java File to Kotlin File. This technique will help you convert code on the whole project effortlessly without much effort.

The Java files will be converted automatically to Kotlin. The plugin won’t work on any Java methods that are not supported by Kotlin, and a red warning mark will appear next to it in Android Studio as seen in Figure 9. In the example code, you could look at the file Crypto.kt.

Figure 9 – a warning about unsupported Java code

That indicates the method may not be supported by Kotlin. So, we need to rewrite some of code.

If you try to run this code, it will generate a compilation error because of not complying with the correct syntax.

Code Conversion And Refactor

While Android Studio converts the whole project’s source code to Kotlin, to migrate from Java to Kotlin, the first thing that you need to be aware of is that Android Studio is still heavily Java oriented. Our mission is to refactor the Kotlin class and also make changes to some of the code structure. There are many tips for refactoring structure of code into Kotlin ways.

Important note

Refactoring existing code from Java to Kotlin without changing the functionality is easiest when you understand both languages.

Remove the code that resembles Java

We have to make sure there aren’t any errors in all of our Kotlin files. You must determine which line results in a file error. In this case, open Crypto.kt and find the following line of code:

companion object {

 val CREATOR: Creator<Crypto> = object : Creator<Crypto?> {

   override fun createFromParcel(`in`: Parcel): Crypto? {

            return Crypto(`in`)

        }

     override fun newArray(size: Int): Array<Crypto?> {

            return arrayOfNulls(size)

        }

    }

}

As you can see, this file contains an error as it didn’t convert perfectly. When we try to convert the entire code to Kotlin, the compiler converts any Java class to a Kotlin class with the same semantics. However, the static method Creator will not convert into Kotlin.

How can we troubleshoot this error? Besides rewriting the code, the easiest way is to delete this function and regenerate it. You can click on the class error warning and when a small red light bulb appears, select Add Parcelable Implementation.

Figure 10 – Adding Parceble Implementation

Android studio will regenerate new functionality method in Kotlin. Here’s what the new method will look like:

 companion object CREATOR : Creator<Crypto> {

    override fun createFromParcel(parcel: Parcel): Crypto {

        return Crypto(parcel)

    }

 

    override fun newArray(size: Int): Array<Crypto?> {

        return arrayOfNulls(size)

    }

}

We can invoke a method without initializing it in Java by making it static. However, in Kotlin, this is not possible. Kotlin doesn’t have a static. Instead, it needs to be replaced with companion object.

Use Safe Calls and Avoid The “!!” Operator

Kotlin provides us with safe calls operator, ?., for accessing properties of the type Nullable. It will return a value if the property is not null. We need to avoid the use of the !! operator in Kotlin because it will throw a NullPointerException if the Nullable reference is null.  The safe calls will be used throughout the Kotlin class and make a little adjustment. The result is the following code:

File:CryptoAdapter.kt

 

    fun init(data: ArrayList<Crypto>?, context: Context?) {

        mContext = context

        mCryptoData.clear()

        data?.let { mCryptoData.addAll(it) }

        notifyDataSetChanged()

    }

 

 

  

        fun bindTo(crypto: Crypto?, context: Context?) {

            textSymbol.text = crypto?.symbol

            textPrice.text = crypto?.currentPrice

            textPercentage.text = context?.resources?.getString(

                R.string.percentage,

                String.format("%s", crypto?.marketCapChangePercentage24h)

            )

            val color   =  crypto?.marketCapChangePercentage24h?.let {

                if (it < 0) {

                    Color.RED

                }

                else {

                    Color.rgb(

                        42,

                        202,

                        39

                    )

                }

            }

            color?.let { textPercentage.setTextColor(it) }

            textName.text = crypto?.name

            imgLogo.setImageUrl(crypto?.image)

        }

The data variable in the first method and the crypto variable in the second method can both return a null value. In this case, we can replace it with safe call operator ?

File:DetailCryptoActivity.kt

        val crypto: Crypto? = intent.getParcelableExtra(EXTRA_CRYPTO)

        logoCrypto = findViewById(R.id.logoCoin)

        symbol = findViewById(R.id.txtSymbolCrypto)

        name = findViewById(R.id.txtNameCrypto)

        price = findViewById(R.id.txtCurrentPrice)

        low = findViewById(R.id.txtLowPrice)

        high = findViewById(R.id.txtHighPrice)

 

        logoCrypto?.setImageUrl(crypto?.image)

        symbol?.setText(crypto?.symbol)

        name?.setText(crypto?.name)

        price?.setText(crypto?.currentPrice)

        low?.setText(crypto?.lowPrice)

        high?.setText(crypto?.highPrice)

To avoid a null value in the crypto variable above, we can use with safe call operator ?

File:MainActivity.kt

        viewModel?.requestData()

        viewModel?.data?.observe(this, { items  ->

            if (items.isNotEmpty()) {

                mAdapter?.init(items, applicationContext)

                swipeRefreshLayout.isRefreshing = false

            }

        })

 

        mAdapter?.setOnItemClick(object : CryptoAdapter.OnItemClick{

            override fun click(crypto: Crypto?) {

                startActivity(

                    Intent(

                        [email protected],

                        DetailCryptoActivity::class.java

                    ).putExtra(DetailCryptoActivity.Companion.EXTRA_CRYPTO, crypto)

                )

            }

 

        })

 

    }

    override fun onRefresh() {

        viewModel?.requestData()

    }

}

Safe calls can also be utilized to perform a null check in a more efficient manner. On other hand, if a value is null, the not-null assertion operator (!!) converts it to a non-null type and throws an exception. Using the safe call operator to protect against null values is strongly advised. Kotlin provides a null safety guide to help you learn more.

Then, without any error notice from Android Studio, your current Java code transforms to Kotlin.

Figure 11 – Kotlin Class after converting from Java

Run and build the apps. The app will work like a charm. You will not have to rewrite the apps from scratch using this method. Android Studio can assist with the conversion of existing Java code to Kotlin. The completed project has been converted may be found at this link https://github.com/Najibsaurus/CryptoWatcher/tree/kotlin

If you’re curious about Kotlin further, You may enhance the quality of your code by using more concise syntax in this link https://github.com/Najibsaurus/CryptoWatcher/tree/kotlin-concise

Summary

In this article, we learned how to port existing Android apps from Java to Kotlin and learned how to refactor the structure of code into the Kotlin way. Finally, we converted a Java project into Kotlin.

A good start is to learn Kotlin in a Kotlin environment. As you know, Google has been promoting Kotlin as primary language. Today, Java remains difficult for many developers and engineers to learn.

If you find Java hard to learn, Kotlin is your best bet. If you’re a newbie and want to learn Kotlin, Google has a course that gets you started. I have seen developers who are familiar with Java finding Kotlin easier to learn.

About the Author

Najib Abdillah is a product manager and developer. Through his career he’s worked on a number of platforms, notably iOS and Android. He is a certified Associate Android Developer.

Give us your feedback

We’d like to know what you thought about the article and if there’s any other tech related content you’d like to see from us: https://www.surveymonkey.com/r/CQW52JK?uuid=[uuid_value]&n=[n_value]

By | 2021-09-01T13:27:54+00:00 September 1st, 2021|Uncategorized|0 Comments

About the Author:

Avatar

Leave A Comment