What is Infix Function in Kotlin: Simple Explanation and Example
infix function in Kotlin is a special kind of function that lets you call it using a simpler syntax without dots or parentheses, making code look cleaner and more readable. It must be a member function or an extension function with a single parameter and marked with the infix keyword.How It Works
Imagine you want to say "A loves B" instead of calling a function like A.loves(B). Kotlin's infix functions let you do exactly that by allowing a function to be called in between two values, like a natural language phrase.
To make a function infix, you add the infix keyword before its definition. This function must take exactly one parameter and be either a member function of a class or an extension function. When you use it, you write the function name between the object and the argument without dots or parentheses, which makes the code easier to read and write.
Think of it like a friendly shortcut that turns a normal function call into a neat phrase, improving code clarity especially when the function represents an action or relationship.
Example
This example shows an infix function shout that adds excitement to a word. Notice how we call it without dots or parentheses.
class Speaker { infix fun shout(message: String): String { return message.uppercase() + "!" } } fun main() { val speaker = Speaker() println(speaker shout "hello") }
When to Use
Use infix functions when you want to make your code more readable and expressive, especially for operations that feel like natural language or simple actions between two things.
Common real-world uses include mathematical operations, building domain-specific languages (DSLs), or expressing relationships like "to", "from", "on", "with" in a clear way. For example, you might use an infix function to say 5 times 3 instead of 5.times(3).
They are best when the function has a single parameter and the call looks cleaner without parentheses.
Key Points
- An
infixfunction must have exactly one parameter. - It can be a member or extension function.
- Called without dots or parentheses for cleaner syntax.
- Improves readability for simple operations or DSLs.
- Cannot be used with functions that have default or vararg parameters.