0
0
Kotlinprogramming~5 mins

Infix functions for readable calls in Kotlin

Choose your learning style9 modes available
Introduction

Infix functions let you write code that reads like a sentence. They make your calls easier to understand.

When you want to make your code look cleaner and more natural.
When you have simple functions with one parameter.
When you want to improve readability in DSLs (Domain Specific Languages).
When you want to chain calls in a way that looks like English.
When you want to avoid using dots and parentheses for simple operations.
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 easy to read.
Kotlin
val result = 3 times "Hi "
Defines an infix function to compare strings in a readable way.
Kotlin
infix fun String.shouldBe(expected: String) = this == expected
Uses the infix function to check equality in a natural style.
Kotlin
val check = "Hello" shouldBe "Hello"
Sample Program

This program defines an infix function 'times' to repeat a string. Then it prints the repeated string.

Kotlin
infix fun Int.times(str: String) = str.repeat(this)

fun main() {
    val message = 2 times "Hello "
    println(message)
}
OutputSuccess
Important Notes

Infix functions improve readability but should be used only when it makes sense.

They cannot have default or vararg parameters.

Use infix functions for simple, clear operations to keep code easy to understand.

Summary

Infix functions let you call functions without dots and parentheses.

They must have exactly one parameter and be member or extension functions.

Use them to make your code look more like natural language.