How to Create Infix Function in Kotlin: Simple Guide
In Kotlin, you create an
infix function by marking a function with the infix keyword and defining it as a member or extension function with a single parameter. This allows you to call the function using infix notation without dots or parentheses, making code more readable.Syntax
An infix function must be a member function or an extension function with exactly one parameter. It is marked with the infix keyword before the function name.
- infix: keyword to enable infix call style
- fun: declares a function
- functionName: name of the function
- parameter: single parameter the function takes
Example syntax:
kotlin
infix fun ClassName.functionName(parameterType) { /* function body */ }Example
This example shows how to create an infix function shout for the String class that repeats the string a given number of times. It demonstrates calling the function using infix notation for cleaner code.
kotlin
infix fun String.shout(times: Int): String {
return this.repeat(times).uppercase()
}
fun main() {
val result = "hello" shout 3
println(result)
}Output
HELLOHELLOHELLO
Common Pitfalls
Common mistakes when creating infix functions include:
- Defining the function with zero or more than one parameter (infix functions must have exactly one parameter).
- Not marking the function with the
infixkeyword. - Trying to use infix notation on functions that are not infix.
Example of a wrong and right way:
kotlin
// Wrong: no infix keyword fun Int.add(x: Int): Int = this + x // Right: with infix keyword infix fun Int.add(x: Int): Int = this + x fun main() { // This will not compile: 1 add 2 // Correct usage: val sum = 1 add 2 println(sum) }
Output
3
Quick Reference
Summary tips for infix functions:
- Use
infixkeyword before function name. - Function must have exactly one parameter.
- Can be member or extension function.
- Call using
object functionName argumentsyntax without dots or parentheses.
Key Takeaways
Mark functions with the infix keyword to enable infix call style.
Infix functions must have exactly one parameter.
You can define infix functions as member or extension functions.
Call infix functions without dots or parentheses for cleaner syntax.
Avoid missing the infix keyword or using wrong parameter counts.