Infix functions
Functions (normal or extension) with just one parameter can be marked as infix
and used with the infix
notation. The infix
notation is useful to express the code naturally for some domains, for example, math and algebra operations.
Let's add an infix
extension function to the Int
type, superOperation
(which is just a regular sum with a fancy name):
infix fun Int.superOperation(i: Int) = this + i fun main(args: Array<String>) { 1 superOperation 2 1.superOperation(2) }
We can use the superOperation
function with the infix
notation or normal notation.
Another area where the infix
notation is commonly used, is on assertion libraries, such as HamKrest (https://github.com/npryce/hamkrest) or Kluent (https://github.com/MarkusAmshove/Kluent). Writing specification code in a natural, easy to understand language is a huge advantage.
Kluent assertions look like natural English expressions:
"Kotlin" shouldStartWith "Ko"
Kluent also comes with a backtick version for even greater...