2019年5月20日 星期一

Kotlin學習筆記(3) Function

Kotlin學習筆記(3)  Function 

fun printMessage(message: String): Unit {                               // 1
    println(message)
}

fun printMessageWithPrefix(message: String, prefix: String = "Info") {  // 2
    println("[$prefix] $message")
}

fun sum(x: Int, y: Int): Int {                                          // 3
    return x + y
}

fun multiply(x: Int, y: Int) = x * y                                    // 4

fun main() {
    printMessage("Hello")                                               // 5                 
    printMessageWithPrefix("Hello", "Log")                              // 6
    printMessageWithPrefix("Hello")                                     // 7
    printMessageWithPrefix(prefix = "Log", message = "Hello")           // 8
    println(sum(1, 2))                                                  // 9
    println(multiply(11, 12))
}


輸出畫面
Hello [Log] Hello [Info] Hello [Log] Hello 3
132


  1. A simple function that takes a parameter of type String and returns Unit (i.e., no return value).
  2. A function that takes a second optional parameter with default value Info. The return type is omitted, meaning that it's actually Unit.
  3. A function that returns an integer.
  4. A single-expression function that returns an integer (inferred).
  5. Calls the first function with the argument Hello.
  6. Calls the function with two parameters, passing values for both of them.
  7. Calls the same function omitting the second one. The default value Info is used.
  8. Calls the same function using named arguments and changing the order of the arguments.
  9. Prints the result of a function call.


沒有留言:

張貼留言

ESP32 遠端感應控制系統

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