2019年5月20日 星期一

Kotlin學習筆記(6) Functions with vararg Parameters

Kotlin學習筆記(6) Functions with vararg Parameters


fun main() {
    printAll("Hello", "Hallo", "Salut", "Hola", "你好")                // 2  
     printAllWithPrefix("Hello", "Hallo", "Salut", "Hola", "你好", prefix = "Greeting: "  // 4

)
        
        
}

fun printAll(vararg messages: String) {                            // 1
    for (m in messages) println(m)
}


fun printAllWithPrefix(vararg messages: String, prefix: String) {  // 3
    for (m in messages) println(prefix + m)
}

fun log(vararg entries: String) {
    printAll(*entries)                                             // 5
}



輸出畫面
Hello
Hallo Salut Hola 你好 Greeting: Hello Greeting: Hallo Greeting: Salut Greeting: Hola Greeting: 你好


  1. The vararg modifier turns a parameter into a vararg.
  2. This allows calling printAll with any number of string arguments.
  3. Thanks to named parameters, you can even add another parameter of the same type after the vararg. This wouldn't be allowed in Java because there's no way to pass a value.
  4. Using named parameters, you can set a value to prefix separately from the vararg.
  5. At runtime, a vararg is just an array. To pass it along into a vararg parameter, use the special spread operator * that lets you pass in *entries (a vararg of String) instead of entries (an Array<String>).

沒有留言:

張貼留言

ESP32 遠端感應控制系統

ESP32 遠端感應控制系統 目前的架構設計(結合了 ESP32、RFID、MQTT、Node-RED 與 Telegram 遠端雙向控制 ),這個系統的核心價值在於 即時感應、雲端中繼、智慧自動化與即時通訊回報 。 整個架構透過無線網路(Wi-Fi),將現場的硬體感測端、雲端訊...