Practical Tips to migrate your Android App to Kotlin
I have seen lots of people converting their tests to Kotlin and then converting other module, But there is no such rule, pick any random file and convert it, check if everything is working as before.
Steps to Convert
Once you know basics of Kotlin
- Convert files, one by one, via “⌥⇧⌘K”, make sure tests still pass.
- Go over the Kotlin files and make them more idiomatic.
- Repeat step 2 until you convert all the files.
Common issues while converting Android App to Kotlin
- TypeCasting for the sake of Interoperability.
Companionwill add extra layer.
- If java method starting with
getX(), converter looks for property with the name
- Generics are hard to get it right on the first go.
- No argument captor.
git diffIf two developers are working on same java file and one guy converts it to Kotlin, it will be rework.
TypeCasting for the sake of Interoperability
Kotlin is not Interoperable right away, but you need to do a lot of work around to make it Interoperable
Here is the Java class:
We need to typecast
String to make it Interoperable with Java.
Companion will add extra layer
Here is Java class:
Converted Kotlin class:
MainActivity method needs to call
DetailsActivity we need to call through Companion which looks ugly in Java code.
Remember: you do not need to stress about migrating the entire codebase. Kotlin and Java can seamlessly interact, and there is no need now to have a 100% Kotlin code. Do it until it feels comfortable.
Method names starting with get
Here is the Java class
Converted Kotlin class is expecting parameters
demoResponse2, They are being interpreted as getter methods, this will cause lots of issues.
If you are using Mockito’s ArgumentCaptor you will most probably get following error
The return value of
classCaptor.capture() is null, but the signature of SomeClass#someMethod(Class, Boolean) does not allow a null argument.
mockito-kotlin library provides supporting functions to solve this problem
annotationProcessormust be replaced by
- Configure tests to mock
- If you are using data-binding, include:
@JvmFieldannotation to use ButterKnife
InjectViewand any testRule field with
@JvmFieldto rescue while using ButterKnife
!! from your Kotlin code
Here is the Kotlin file with full of
Here is the updated Kotlin class with removal of
Don’t try to learn the whole language at once
Migrating you existing codebase to Kotlin will be fun and needs lot of patience but it will be worth the effort. Make sure you have some unit tests in your existing codebase to migrate with less hassle.
kotlin-android-starter - [Kotlin Android] Kotlin Android starter based MVP/Dagger2/RxJava2/Robolectric/Espresso/Mockito…github.com