English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin 中缀函数(infix)

In diesem Artikel werden Sie lernen, wie man Funktionen in Kotlin mit infix Symbolen aufruft (mit Beispielen).

Bevor wir lernen, wie man Funktionen mit infix notation erstellt, lassen Sie uns zunächst zwei häufig verwendete infix-Funktionen untersuchen.

Bei der Verwendung von || und &&& sucht der Compiler nach den or- und and-Funktionen und ruft sie im Hintergrund auf.

Diese beiden Funktionen unterstützen infix notation.

Beispiel: Kotlin or & and Funktionen

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")
}

Wenn das Programm ausgeführt wird, wird ausgegeben:

result = true
result = false

Im obigen Programm wird a or b anstelle von a.or(b) und a and b anstelle von a.and(b) verwendet. Dies ist erlaubt, da diese beiden Funktionen infix notation unterstützen.

Wie erstelle ich eine Funktion mit infix notation?

Sie können in Kotlin Funktionsaufrufe mit infix notation verwenden, wenn die Funktion

  • istMitgliedsfunktion(oderErweiterungsfunktion).

  • Hat nur einen Parameter.

  • mit dem Schlüsselwort infix markiert.

Beispiel: Benutzerdefinierte Funktion mit infix notation

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)
}

Wenn das Programm ausgeführt wird, wird ausgegeben:

      * 
    * * * 
  * * * * * 
* * * * * * *

Hier ist createPyramid() eine infix-Funktion, die Pyramidengebäude erstellt. Es ist eine Memberfunktion der Structure-Klasse und akzeptiert nur einen Int-Typ Parameter, der mit dem Schlüsselwort infix beginnt.

Pyramidenzeilen hängen von den Parametern ab, die an die Funktion übergeben werden.