Extension Functions in Kotlin
Imagine that, somewhere in your code, you need to extend a class with new functionality. For most programming languages, your options would be to either derive a new class or make use of some kind of design pattern. But with Kotlin, things are different—we’ve got another option on the table.
In Kotlin, there’s something called an extension function which can be used to extend a class and give it new functionality. More or less, an extension function is a member function of a class, but one that is defined outside that class.
Kotlin isn't entirely alone in this; languages like C# and Gosu also give us the ability to extend a class with new functionality without having to use inheritance or a design pattern. In Kotlin, we do this by way of a special type of declaration called an extension. Kotlin makes use of both extension functions and extension properties.
By wielding the power of extensions, we can both add and remove functionality. Extensions are resolved statically and do not actually modify the classes they extend. Rather, they create a callable function that is called using the dot operator.
If all this sounds confusing, don’t worry—it’s actually pretty easy to use extension functions in Kotlin. We’ll look at examples for function and object extensions and you’ll see what I’m talking about.
Function Extension
With function extensions, Kotlin lets us define a method outside the main class. Have a look at how the extension is implemented at the functional level.
class Hobbyist {
var hobbies : String = "null"
fun printMyHobbies() {
print(hobbies)
}
}
fun main(args: Array<String>) {
var a1 = Hobbyist()
a1.hobbies = "Yoga"
//a1.printMyHobbies()
var a2 = Hobbyist()
a2.hobbies = "Rafting"
//a2.printMyHobbies()
var a3 = Hobbyist()
a3.hobbies = a1.addMyHobbies(a2)
a3.printMyHobbies()
}
fun Hobbyist.addMyHobbies(a:Hobbyist):String{
var a4 = Hobbyist()
a4.hobbies = this.hobbies + " " +a.hobbies
return a4.hobbies
}
In this example, there is no method inside of the Hobbyist class that’s called addMyHobbies. Yet we can still implement that method somewhere else outside of the class. This is the mighty power of extensions in Kotlin.
Here is what the code above will return:
Yoga Rafting
Object Extension
Kotlin gives us another mechanism for implementing the static functionality of Java. To do this, we use the keyword “companion object.” Using this feature of Kotlin, we can make an object of a class inside a Kotlin factory method. Then we can call that method just by using the class name. If that sounds complicated, have a look at this example and it should all be clear. We’ll create a companion object.
fun main(args: Array<String>) {
println("I'm learning about... "+A.show())
}
class A {
companion object {
fun show():String {
return("Extension functions in Kotlin!")
}
}
}
This block of code here will return the following output:
I'm learning about... Extension functions in Kotlin!
This example seems a lot like static Java. But here, we’re creating an object in real-time that’s a member variable of that same class. This is why it’s also included under the extension property and can also be called an object extension. Really, what we’re doing is extending the object of the same class to use its member functions.
Conclusion
Extensions are a great feature in Kotlin and when used correctly can make for clean, elegant code. However, we should avoid overusing extension or using them at the wrong time. Kotlin extensions are best used for extending existing abstractions but shouldn’t be used to try to smooth over bad or missing abstractions.
Check back soon for our next article where we’ll look at both data and sealed abstractions.
Previous Article: Visibility Modifiers | Next Article: data & sealed classes |
Recent Stories
Top DiscoverSDK Experts
Compare Products
Select up to three two products to compare by clicking on the compare icon () of each product.
{{compareToolModel.Error}}
{{CommentsModel.TotalCount}} Comments
Your Comment