Improve Java to Kotlin code review

Picture by Fatos Bytyqi on Unsplash

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 to else, as it will get triggered if the previous if true result still return a null.

toolbar?.title =…

--

--