2019年5月20日 星期一

Kotlin學習筆記(4) infix Functions 内缀函数

Kotlin學習筆記(4)  infix Functions 内缀函数

infix Functions 内缀函数
Member functions and extensions with a single parameter can be turned into infix functions.

程式 

fun main() {

  infix fun Int.times(str: String) = str.repeat(this)        // 1
  println(3 times "Bye ")                                    // 2

  val  pair = "1. Ferrari" to "2. Katrina"                          // 3
  println(pair)

  infix fun String.onto(other: String) = Pair(this, other)   // 4
  val myPair = "McLaren" onto "Lucas"
  println(myPair)

  val sophia = Person("Sophia")
  val claudia = Person("Claudia")

  sophia likes claudia                                       // 5

 
}

class Person(val name: String) {
  val likedPeople = mutableListOf<Person>()
  infix fun likes(other: Person) { likedPeople.add(other) }  // 6
}
輸出畫面
Bye Bye Bye (1. Ferrari, 2. Katrina) (McLaren, Lucas)


  1. Defines an infix extension function on Int.
  2. Calls the infix function.
  3. Creates a Pair by calling the infix function to from the standard library.
  4. Here's your own implementation of to creatively called onto.
  5. Infix notation also works on members functions (methods).
  6. The containing class becomes the first parameter.

沒有留言:

張貼留言

RFID TI 培訓影片系列

RFID TI 培訓影片系列  https://www.ti.com/zh-tw/video/series/rfid.html 培訓影片系列 RFID 隨著創新技術日益發展,RFID 和 RF 術語越來越容易讓人混淆。本訓練系列詳細介紹了使用案例、權衡技術優缺點,讓您清楚知道該選...