How do you define extension functions in Kotlin?
Extension functions in Kotlin are a powerful feature that allows you to add new functionality to existing classes without directly modifying their source code. They provide a convenient way to extend the behavior of classes, including standard library classes or even classes defined in third-party libraries.
To define an extension function in Kotlin, you simply prefix the function name with the name of the class you want to extend, followed by a dot (.). Here’s a basic example of an extension function:
kotlin fun String.addHelloPrefix(): String { return "Hello, $this" }
In this example, addHelloPrefix() is an extension function defined for the String class. It prefixes the given string with “Hello, “.
Extension functions can be defined in any Kotlin file, including the main source file or separate utility files. They provide a clean and concise way to enhance the functionality of existing classes without altering their original implementation, promoting code maintainability and readability.