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.

沒有留言:

張貼留言

WOKWI LED + MQTT Node-Red SQLite

WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...