Improve Java to Kotlin code review
Published in
4 min readMar 25, 2020
In Android Studio, we could easily convert our Java code to Kotlin using Shift-Option-Command-K key. In a split of the second, Java code is now Kotlin.
But… it is Java-Style Kotlin. How could we improve that? What to look out to change? Below are a few tips to clean it up…
Look out for double bang !!
Remove double bang
myList!!.length
See if myList
can change to non-nullable. If not, change to a null check accordingly.
myList?.length
Null check code before execution
if (callback != null) {
callback!!.response()
}
change to
callback?.response()
Use Elvis expression carefully
if (toolbar != null) {
if (arguments != null) {
toolbar!!.title = arguments!!.getString(TITLE)
} else {
toolbar!!.title = ""
}
}
Here we could use Elvis Expression
Be careful
?:
is not equivalent toelse
, as it will get triggered if the previousif
true
result still return anull
.
toolbar?.title =…