Infix in Kotlin. A very neat and highly underused… | by Deepak Nair

Posted on
Photo by Chris Liverani on Unsplash

A very neat and highly underused feature of Kotlin is infix notations. After stumbling upon in it randomly, it’s become one of my favourite features.

Infix functions are:

  • incredibly easy to learn
  • quick to write/migrate
  • write unbelievable syntax when paired with Extension function

What are infix expressions ?

Consider a function being called:

fun Long.add(number: Long) {
return this + number
val num = 10
val newnum = num.add(5)

Adding infix function at the start — we can call it like:

infix fun Long.add(number: Long) {
return this + number
val num = 10
val newnum = num add 5

instanceOf func is an example of a built in expression

Writing your own infix expression

Infix keyword works only for functions that have one parameter

Let’s take a function to reverse a string , isRevInfix uses the same function but in an infix syntax and magical to read !

not pseudo but actual code !

There can be many other intuitive examples !!

a doesNotHaveAnAppointmentOn “Sunday”

a endsWith “a”

a beginsWith “c”

a hasSubString “d”

a isContainedIn “personList”

date isBetween Pair<startDate(),endDate()>

and the list goes on …

Cases where you can really see infix makes a difference in your code

  • complex business logic with multiple if cases are unavoidable e.g.)
use of a ‘but’ condition almost seem like english statement and much more easy to read
  • isA/hasA relationShip
  • makes leetcoding a lot more fun e.g) a isALeafNodeOf binaryTree

Happy Infixing !

Leave a Reply

Your email address will not be published.