Kotlin is a statically typed programming language for the JVM, Android and the browser. It is known for its interoperability, safety, tooling support, and concise syntax.
One of the most powerful features of Kotlin is extension functions. Extension functions are functions that are added to existing classes, without having to inherit from them. This means that you can add new functionality to existing classes, without having to modify the class itself.
In this article, we'll take a look at how to create extension functions, and how they can be used to enhance existing classes.
Creating an extension function is simple. All you need to do is prefix the function name with the name of the class you want to extend, followed by a dot. For example, to create an extension function that adds a print()
method to the String
class, you would do the following:
fun String.print() {
println(this)
}
Now, you can call the print()
method on any string, like so:
"Hello, world!".print() // prints "Hello, world!"
As you can see, extension functions are a great way to add new functionality to existing classes.
Extension functions are particularly useful when you want to add new methods to a class that you don't have control over. For example, let's say you're using a library that has a User
class, but you want to add a getFullName()
method to it. With extension functions, you can do this without having to modify the User
class itself.
First, let's define a User
class:
class User(val firstName: String, val lastName: String)
Now, we can create an extension function that adds a getFullName()
method to the User
class:
fun User.getFullName(): String {
return "$firstName $lastName"
}
Now, we can create a User
object and call the getFullName()
method on it:
val user = User("John", "Smith")
println(user.getFullName()) // prints "John Smith"
As you can see, extension functions are a great way to add new methods to existing classes, without having to modify the class itself.
In this article, we've taken a look at extension functions in Kotlin. We've seen how to create extension functions, and how they can be used to add new methods to existing classes.