Organize Kotlin’s extension functions

Kevin Schweitzer
ProAndroidDev
Published in
2 min readDec 18, 2018

--

As there are a lot of posts talking about extension functions in Kotlin, this post won’t talk about how to use them. The aim of this post is to avoid throwing the extensions functions wherever in the code.

If you are in a class called MyClass and write something like

MyClass { fun someMethod(textView: TextView){
textView.extensionMethod()
}
}

without defining the extension, Android Studio will show you an error, and if you see the suggestions it will say “Create extension function”, so if you click there, the extension function will be defined within the same class:

This is a problem, because the extension functions will grow in quantity and we will have a lot of extensions dispersed all around the code.

The correct way to do this would be having files where we can define the extensions. If we have only a few we can have only one file, if not, we can have files like “TextViewExtension” only for extensions for TextView and so on.

The important thing here is that we need to create a Kotlin File, NOT a Kotlin Class.

As you now, when you define a method in a class you have to call MyClass().someMethod() and that’s not what we want for extension methods, so we have to create a file in New > Kotlin File/Class

Once you have the file, you can define inside it the extension function and use it everywhere in the code.

Extensions.kt
MyClass.kt

That’s all for now, keep improving code and organizing things better. You can read my post about organizing gradle files here
Greetings!

--

--