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.
Companion
will add extra layer.- If java method starting with
getX()
, converter looks for property with the nameX
. - Generics are hard to get it right on the first go.
- No argument captor.
git diff
If 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 message
as String
to make it Interoperable with Java.
Companion
will add extra layer
Here is Java class:
Converted Kotlin class:
When 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 demoResponse
and demoResponse2
, They are being interpreted as getter methods, this will cause lots of issues.
No ArgumentCaptor
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
Key Takeaways
annotationProcessor
must be replaced bykapt
inbuild.gradle
- Configure tests to mock
final
classes - If you are using data-binding, include:
kapt com.android.databinding:compiler:3.0.0-alpha8
- Use
@JvmField
annotation to use ButterKnifeInjectView
and any testRule field with@Rule
annotation. @JvmField
to rescue while using ButterKnife@InjectView
and Espresso@Rule
Eliminate all !!
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.