Extension functions usage


Hello, I noticed that extension functions are widely used in Kotlin default library i.e. Kotlin String class contains just few basic methods, but a lot of other methods are implemented as extension functions. I thought that extension functions were ment to be helpers for those who don't have access to source but still want nice helper methods for some classes. I can see only one reason for this usage of extension function - to reduce number of autocomplete options when some packages are not imported. But as for me it makes usage of such classes too complicated. Can you tell about the idea of extension functions some more details if there are those?

I also have a problem with this particular case:


package test;

import std.io.println
import kotlin.*

fun main(args : Array<String>) {

this code is not compiled as matches() extension functions cannot be found. I thought there is an issue with imports and I search for an example in Kotlin sources. I found some and added import kotlin. but it did help. There was also a kotlin.util.* import there but it can not be resolved in my case.
Thanks in advance.


What version of Kotlin plugin and runtime do you using?

It works at the latest build from sources.


I use plugin 0.1.1844 and runtime comes with it. It was the last stable build for today.


Dont you think that extension functions are a nice way to augment the jdk ?


Yes they are and not only JDK but all the other libraries. But what I mean here is that they are used for example to imlement matches() method in Kotlin String class. And this usage is not obvious for me.


Do you mean that   inline fun String.matches(regex : String) = (this as java.lang.String).matches(regex).sure() is not obvious ?


The usage of extension function is not obvious in this case. String here is a Kotlin class so the same method can be implemented inside it so as others from String.kt.


So what could be a better alternative ?


String here is a Kotlin class so the same method can be implemented inside it so as others from String.kt.


I'm guessing the question asked here is more one of good practice: when you have the source of the class you are trying to augment, when should you just add your method there instead of using an extension method?


Ok got it. I wonder if the bytecode output will be 100% the same with both methods.


It defenetely is not: Class functions generate common methods inside classes. Extension functions generate outside static method with additional reciever parameter.


It's good to keep APIs of your classes minimal. With extension functions you can have all the convenience of a rich API, but having only necessary things actually exposed from your class. One other thing is that if you don't like the set of extensions Kotlin provides today (e.g. funciton names are confusing or soething else bothers you), you can skip those and use some other set of extensions to String.