English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to call functions with infix symbols in Kotlin (with examples).
Before learning how to create functions with infix notation, let's first study two commonly used infix functions.
When using || and &&& operations, the compiler looks up the or and and functions respectively, and calls them in the background.
These two functions support infix notation.
fun main(args: Array<String>) { val a = true val b = false var result: Boolean result = a or b // a.or(b) println("result = $result") result = a and b // a.and(b) println("result = $result") }
When the program is run, the output is:
result = true result = false
In the above program, use a or b instead of a.or(b), and use a and b instead of a.and(b). This is allowed because these two functions support infix notation.
You can use infix notation to call functions in Kotlin if the function
isMember function(orExtension function).
It has only one parameter.
Marked with the infix keyword.
class Structure() { infix fun createPyramid(rows: Int) { var k = 0 for (i in 1..rows) { k = 0 for (space in 1..rows-i) { print(" ") } while (k != 2*i-1) { print("* ) ++k } println() } } } fun main(args: Array<String>) { val p = Structure() p createPyramid 4 // p.createPyramid(4) }
When the program is run, the output is:
* * * * * * * * * * * * * * * *
Here, createPyramid() is an infix function that creates a pyramid structure. It is a member function of the Structure class, accepts a single Int type parameter, and starts with the infix keyword.
The number of rows in the pyramid depends on the parameter passed to the function.