0
0
Kotlinprogramming~5 mins

Infix functions in DSLs in Kotlin

Choose your learning style9 modes available
Introduction

Infix functions let you write code that looks like natural language. They make your code easier to read and write, especially in small, special languages inside Kotlin called DSLs.

When you want to create a simple, readable way to combine two values or actions.
When building a small language inside Kotlin to describe something clearly, like building HTML or queries.
When you want to call a function with one argument without using dots or parentheses.
When you want your code to look like a sentence for better understanding.
When you want to improve the style of your Kotlin code for specific tasks.
Syntax
Kotlin
infix fun functionName(parameter: Type): ReturnType {
    // function body
}

The function must be a member function or an extension function.

It must have exactly one parameter.

Examples
This defines an infix function times that repeats a string a number of times.
Kotlin
infix fun Int.times(str: String) = str.repeat(this)
Calls the infix function without dots or parentheses, making it look like natural language.
Kotlin
val result = 3 times "Hi"
An infix function to check if a string matches an expected value, useful in tests or DSLs.
Kotlin
infix fun String.shouldBe(expected: String) {
    if (this != expected) throw AssertionError("Expected $expected but got $this")
}
Sample Program

This program defines a Robot class with an infix function moves. It lets you write robot moves "forward" instead of robot.moves("forward"), making it easier to read.

Kotlin
class Robot {
    infix fun moves(direction: String) = "Robot moves $direction"
}

fun main() {
    val robot = Robot()
    println(robot moves "forward")
}
OutputSuccess
Important Notes

Infix functions improve readability but should be used only when it makes the code clearer.

They can only have one parameter, so they are simple by design.

Use infix functions to create small, easy-to-read DSLs inside Kotlin.

Summary

Infix functions let you call functions with one argument without dots or parentheses.

They make code look like natural language, great for DSLs.

Use them to write clearer and more readable Kotlin code.