2019年5月20日 星期一

Kotlin學習筆記(5) Operator Functions

Kotlin學習筆記(5) Operator Functions


fun main() {
operator fun Int.times(str: String) = str.repeat(this)       // 1
println(4 * "Bye ")                                          // 2

operator fun String.get(range: IntRange) = substring(range)  // 3
val str = "Always forgive your enemies; nothing annoys them so much."
println(str[0..14])                                          // 4
}

Bye Bye Bye Bye Always forgive

  1. This takes the infix function from above one step further using the operator modifier.
  2. The operator symbol for times() is * so that you can call the function using 2 * "Bye".
  3. An operator function allows easy range access on strings.
  4. The get() operator enables bracket-access syntax.

沒有留言:

張貼留言

2026 作業3 RFID+ Telegram 練習

 2026 作業3  RFID+ Telegram  練習 (Wokwi 與 Telegram 二者溝通訊息反映比較慢 ) 歡迎 Alex 使用 RFID 控制系統 /on : 開啟 LED /off : 關閉 LED /flash : 閃爍模式 /timer : 開啟 5 秒 ...