# 有趣的 Kotlin 0x06：List minus list

【有趣的 Kotlin 】系列记录自己对每一题的理解。

## 0x06：List minus list

``````fun main(args: Array<String>) {
val list = listOf(1, 2, 3)
print(list - 1)
print(list - listOf(1))
​
val ones = listOf(1, 1, 1)
print(ones - 1)
print(ones - listOf(1))
}

1. [2, 3][2, 3][1, 1][1, 1]
2. [2, 3][2, 3][1, 1][]
3. [2, 3][2, 3][][1, 1]
4. [2, 3][2, 3]

## 分析

``````fun main(args: Array<String>) {
val list = listOf(1, 2, 3)
print(list.minus(1))
print(list.minus(listOf(1)))
​
val ones = listOf(1, 1, 1)
print(ones.minus(1))
print(ones.minus(listOf(1)))
}

``````val list = listOf(1, 2, 3)
print(list - 1)           // 过滤掉第一个等于 1 的元素，结果为 [2, 3]
print(list - listOf(1))   // 过滤掉所有等于 1 的元素，结果为 [2, 3]
​
val ones = listOf(1, 1, 1)
print(ones - 1)           // 过滤掉第一个等于 1 的元素，结果为 [2, 3]
print(ones - listOf(1))   // 过滤掉所有等于 1 的元素，结果为 []

## 延伸

`Kotlin` 中使用 `operator` 关键字用于修饰函数，表示该函数重载一个操作符或者实现一个约定。使用 `operator` 关键字修饰函数并且函数名只能为`component1``component2``component3` … 时则是实现一个约定，即 `解构`

``````fun main() {
val list = listOf(1, 2, 3)
println(2 in list)
println(4 in list)
println(list + 5)
println(list + listOf(1, 2, 3))
println(list + arrayOf(1, 2, 3))
println(list + sequenceOf(1, 2, 3))
​
val (v, w, x) = list
println(v)
println(w)
println(x)

println(list.component1())
println(list.component2())
println(list.component3())
println(list.component4())
println(list.component5())
​
}

componentN 最多支持到 5， 且 receiver 为 List，内部其实调用的就是 `get()` 函数，所以当索引超出列表长度时，运行时报错。

``````class Location(val x: Int, val y: Int) {
operator fun component1() = x
operator fun component2() = y
}
​
fun main() {
val location = Location(520, 1314)
val (x, y) = location
​
println(x)
println(y)
}

``````operator fun Location.minus(location: Location): Location {
return Location(this.x - location.x, this.y - location.y)
}
​
operator fun Location.plus(location: Location): Location {
return Location(this.x + location.x, this.y + location.y)
}
​
operator fun Location.contains(location: Location): Boolean {
return this.x > location.x && this.y > location.y
}
​
​
class Location(val x: Int, val y: Int) {
operator fun component1() = x
operator fun component2() = y
​
override operator fun equals(other: Any?): Boolean =
other is Location && this.x == other.x && this.y == other.y
​
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
​
override fun toString(): String {
return "(\$x, \$y)"
}
}
​
fun main() {
val location = Location(520, 1314)
val (x, y) = location
​
println(x)
println(y)
​
val other = Location(1, 2)
println(location - other)
println(location + other)
println(location == other)
println(other in location)
}

• 操作符重载
• 解构

Android