-1

The Kotlin language brings the simplification of function calls to the natural language. This article shows a nice example:

  • Function:
    fun of(suit: Suit) = Card(this, suit)
    
    val card = Rank.QUEEN.of(Suit.HEARTS)
    
  • Infix function:
    infix fun of(suit: Suit) = Card(this, suit)
    
    val card = QUEEN of HEARTS
    

AS a newbie to Kotlin, I can imagine myself writing every function as an infix function, yet my intuition says it is wrong. There is endless supply of tutorials about how to write and use infix functions, but none of them explain the proper use cases.

Is there a rule of thumb on when it is appropriate to use an infix function and when not?

1 Answer 1

2

infix should be treated like the syntactic sugar that it is: If it aids in the readability and flow of your code? Use it. Otherwise? Don't. That's really the only hard/fast rule. Mind that just b/c you can add infix doesn't mean you should. So while you could, through a series of complex higher order functions, generics, and callbacks, architect your code in a manner that allows you to write dog bark at cat 4 times, it's likely easier and more maintainable (and less burdensome on your compatriots) to write dog.barkAt(cat, times=4)

Personally, I find infix most useful when creating unit tests since I only really want to understand the gist of what's happening, and not the details.

Not the answer you're looking for? Browse other questions tagged or ask your own question.