2

It´s a good idea to use kotlin extensions all over the code?

  1. I miss a lot the extensions from iOS, but this is a good way to use those kind of things in android? Refering to http://antonioleiva.com/kotlin-android-extension-functions/

  2. Is there a better solution for this?

Daniel Gomez Rico
  • 15,026
  • 20
  • 92
  • 162

2 Answers2

4

Extension functions in Kotlin are compiled to normal Java methods. For example, when you define a function in your package it turns into a static method in a Java class. There's no overhead compared to simply calling a static utility

Andrey Breslav
  • 24,795
  • 10
  • 66
  • 61
  • It's a good idea to use `Kotlin` just for Extensions over an existing `Android Java project`? – Daniel Gomez Rico Apr 16 '15 at 22:19
  • Yes. I suggest you to use my own [library](https://github.com/yoavst/androidKotlin) and [kotlin's one](http://kotlinlang.org/docs/tutorials/android-plugin.html) – Yoavst Apr 17 '15 at 10:57
4

To expand a little bit more on Andrey Breslav's answer a bit, Kotlin extension functions do compile down to static java methods, so most general purpose extension functions carry no overhead. But there is one edge case you need to look out for that Jake Wharton calls out in the first few min of this talk at Google IO.

That is when you pass in higher order functions (lambdas), as a parameter to the extension function like so:

fun View.doSomething(block: () -> Unit) {
    //do something 
}

This code would take a performance hit because lambda's under the hood have to create an anonymous class under the hood which can eat up methods and cause class loading. This is a very simple fix by adding the inline keyword to the function which will essentially inline your code into all of this call sites functions so you will not take a performance hit each time the extension function is called.

inline fun View.doSomething(block: () -> Unit) {
    //do something 
}
Andrew Steinmetz
  • 1,010
  • 8
  • 16