Infix Function Kotlin
--
Introduction
Kotlin is a language that adds many fresh features to allow the writing of cleaner, easier-to-read code. This, in turn, makes our code significantly easier to maintain and allows for a better end result from our development. Infix notation is one of such features.
What Is an Infix Notation?
Kotlin allows some functions to be called without using the period and brackets. These are called infix methods, and their use can result in code that looks much more like a natural language.
Example: Kotlin or & and Function
fun main(args: Array<String>) {
val a = true
val b = false
var result: Boolean
result = a or b // same as a.or(b)
println("result = $result")
result = a and b // same as a.and(b)
println("result = $result")
}
The program output will be:
result = true
result = false
How to create a function with infix notation?
You can make a function call in Kotlin using infix notation if the function
- is a member function (or an extension function).
- has only one single parameter.
- is marked with
infix
keyword.
Example: User-defined Function With Infix Notation
class Pattern() {
infix fun createPattern(rows: Int) {
var j = 0
for (i in 1..rows) {
j = 0
for (space in 1..rows-i) {
print(" ")
}
while (j != 2*i-1) {
print("* ")
++j
}
println()
}
}
}
fun main(args: Array<String>) {
val p = Pattern()
p createPattern 3 // same as p.createPattern(4)
}
The program output will be:
*
* * *
* * * * *
Here, createPattern()
is an infix function that creates a pyramid structure. It is a member function of class Pattern
, takes only one parameter of type Int
, and starts with keyword infix
.
The number of rows of the pattern depends on the argument passed to the function.
Summary
This quick tutorial shows some of the things that can be done with infix functions, including how to make use of some existing ones and how to create our own to make our code cleaner and easier to read.