Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

What's the actual point of making a function infix?

You've probably already used infix functions without realizing it. Every time you create a Map using "Key" to "Value", you're using the to infix function. The primary goal here isn't to add new functionality—anything an infix function can do, a regular function can also do—it's entirely about readability.

I usually reach for infix functions when I'm building a Domain Specific Language (DSL) or when I want the code to read like a natural sentence. Take a look at this example where we're handling simple distance measurements. Compare the two styles:

class Distance(val value: Int, val unit: String) {
    infix fun convertTo(newUnit: String): Distance {
        // Imagine some actual conversion logic here
        return Distance(value * 2, newUnit) 
    }
}

val homeToWork = Distance(5, "miles")

// Standard call: feels like "code"
val metricDistance = homeToWork.convertTo("kilometers")

// Infix call: feels like a sentence
val metricDistanceInfix = homeToWork convertTo "kilometers"

In a small project, it doesn't matter much. But in a large codebase where you're expressing complex business rules, removing the dots and parentheses can significantly lower the cognitive load for the person reading your code.

Can I turn any function into an infix one?

Not exactly. The Kotlin compiler is pretty strict about what qualifies. If you try to mark a function as infix and it doesn't meet these three criteria, it'll throw an error immediately:

  • It must be a member function or an extension function. You can't just have a top-level function be infix.
  • It must have exactly one parameter. No more, no less. If you need two parameters, you're out of luck; you'll have to use a regular function or a data class to wrap those parameters.
  • The parameter cannot have a default value and cannot be a vararg.

I've seen developers try to cheat this by passing a Pair or a List as the single parameter just to get more data in there. I'd advise against that. Once you start doing that, you've lost the "natural language" feel that makes infix functions worthwhile in the first place.

How does precedence work when I mix these with other operators?

This is where things can get trippy. Infix functions have lower precedence than arithmetic operators, but higher precedence than logical operators or comparisons.

If you're doing something like 10 + 5 convertTo "km", Kotlin handles the + first because math always wins. However, if you mix it with something like && or ||, the infix function happens first. I'll be honest: if your expression gets complex enough that you're worrying about the precedence of a custom infix function, you should probably just use parentheses. Even if the compiler knows what to do, your teammates probably won't.

// This is clear: (10 + 5) is evaluated, then convertTo is called.
val result = 10 + 5 convertTo "km" 

// This is a nightmare to read:
if (dist1 convertTo "km" > 10 && dist2 convertTo "km" > 20) { 
    /* ... */ 
}

Keep your infix calls simple. If the line of code starts looking like a math equation from a college textbook, you've gone too far.




📋 Practical Task

Implementing a Smart Home Command DSL

You are building a system to control smart home devices. Your goal is to make the command sequence look like natural language using infix functions.

Create a class Device that takes a name: String. Inside this class, implement an infix function called setPower that takes a Boolean value. The function should print a message like: "Setting [deviceName] power to [on/off]".

Then, create an extension infix function for the Device class called toLevel that takes an Int. This function should print: "Setting [deviceName] level to [value]".

Finally, in your main function, instantiate a Device("Living Room Lamp") and use the infix notation to set its power to true and its level to 80 in two separate lines without using dots or parentheses.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.