Extensions let you add new features to existing code easily. For DSLs, they help make code look simple and natural, like a special language just for your task.
Extensions for DSL building in Kotlin
fun ReceiverType.extensionFunctionName(params) { // function body }
ReceiverType is the class you add the function to.
This function can be called as if it belongs to the receiver object.
shout to String that makes text uppercase and adds an exclamation.fun String.shout() = this.uppercase() + "!"
fun MutableList<Int>.addTwice(value: Int) { this.add(value) this.add(value) }
jump action to the Robot class without changing its code.class Robot { fun move() = println("Moving") } fun Robot.jump() = println("Jumping")
This program shows how to add a new jump function to the Robot class using an extension. The robot can move and jump.
class Robot { fun move() = println("Moving") } fun Robot.jump() = println("Jumping") fun main() { val robot = Robot() robot.move() robot.jump() }
Extensions do not actually change the original class; they just add new functions you can use.
If an extension function has the same name as a member function, the member function is called instead.
Extensions help make DSLs by letting you write code that reads like natural instructions.
Extensions add new functions to existing classes without changing them.
They help create simple and readable DSLs by making code look like a special language.
Use extensions to organize code and improve clarity when building complex objects.