Kotlin: The Good, The Bad, and The Ugly

AJ Alt
AJ Alt
Aug 19, 2016 · 14 min read

The Good

Automatic conversion of Java to Kotlin

lateinit, Delegates.notNull and lazy

val name: String
var name: String? = null
lateinit var name: String
var age: Int by Delegates.notNull<Int>()
val imm: InputMethodManager by lazy { 
getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
}

Functional collection extensions

Named and default function arguments

class Presenter(
val okhttp: OkHttp = productionOkHttp(),
val picasso: Picasso = productionPicassoInstance()
) {...}

The Bad

No namespaces

fun foo() {...}
object FooActions {
fun foo() {...}
}

No static modifier

public class View {
public static final int VISIBLE = 0x00000000;
public static final int INVISIBLE = 0x00000004;
public static View inflate(Context context, int resource) {...}
}
class View {
companion object {
@JvmField
val VISIBLE: Int = 0x00000000
@JvmField
val INVISIBLE: Int = 0x00000004
@JvmStatic
fun inflate(context: Context, resource: Int) {...}
}
}
// With annotations:
View.VISIBLE;
//Without annotations:
View.Companion.getVISIBLE();

Automatic conversion of Java to Kotlin

Required property accessor syntax

Method count


The Ugly

SAM conversion and Unit returning lambdas

public void registerCallback(View.OnClickListener r)
// Java
registerCallback(() -> { /** do stuff */ })
//Kotlin
registerCallback { /** do stuff */ }
fun registerCallback(r: View.OnClickListener)// Kotlin. Note that parenthesis are required now.
registerCallback(View.OnClickListener { /** do stuff */ })
fun registerCallback(r: () -> Unit)
registerCallback(() -> {
/** do stuff */
return Unit.INSTANCE;
})

Closed by default

“Best practices say that you should not allow these hacks anyway”

“People successfully use other languages (C++, C#) that have similar approach”

“If people really want to hack, there still are ways: you can always write your hack in Java and call it from Kotlin (see Java Interop), and Aspect frameworks always work for these purposes”

Conclusion


Keepsafe Engineering

Engineering problems at Keepsafe.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store