seo關于網站b站2023推廣網站
在Kotlin中,常用的運算符重載函數名如下:
1.算術操作符:
加法:plus
減法:minus
乘法:times
除法:div
取模:rem 或 mod
整數除法:floorDiv
求冪:pow
自增:inc
自減:dec
2.比較操作符:
等于:equals 或 ==
不等于:notEquals 或 !=
大于:greater 或 >
小于:less 或 <
大于等于:greaterEquals 或 >=
小于等于:lessEquals 或 <=
3.索引操作符:
獲取元素:get
設置元素:set
4.調用操作符:
調用:invoke
5.包含操作符:
包含:contains
6.類型轉換操作符:
類型轉換:as
7.賦值操作符:
賦值:set
8.一元操作符:
正號:unaryPlus
負號:unaryMinus
邏輯非:not
以上是一些常用的運算符重載函數名。需要注意的是,這些函數名是Kotlin語言規(guī)范的一部分,開發(fā)者應該遵循這些規(guī)則來定義運算符的行為。
下先舉個簡單的例子:
- 算術操作符
我們可以為自定義類定義加法、減法、乘法和除法操作符的行為。
data class Point(val x: Int, val y: Int) {operator fun plus(other: Point): Point {return Point(x + other.x, y + other.y)}operator fun minus(other: Point): Point {return Point(x - other.x, y - other.y)}operator fun times(other: Int): Point {return Point(x * other, y * other)}operator fun div(other: Int): Point {return Point(x / other, y / other)}
}fun main() {val p1 = Point(1, 2)val p2 = Point(3, 4)val p3 = p1 + p2 // 相當于 p1.plus(p2)val p4 = p1 - p2 // 相當于 p1.minus(p2)val p5 = p1 * 2 // 相當于 p1.times(2)val p6 = p1 / 2 // 相當于 p1.div(2)println(p3) // 輸出: Point(x=4, y=6)println(p4) // 輸出: Point(x=-2, y=-2)println(p5) // 輸出: Point(x=2, y=4)println(p6) // 輸出: Point(x=0, y=1)
}
2.索引操作符
我們可以為自定義類定義索引操作符[]的行為。
class MyList<T>(vararg elements: T) {private val list = elements.toMutableList()operator fun get(index: Int): T {return list[index]}operator fun set(index: Int, value: T) {list[index] = value}
}fun main() {val myList = MyList(1, 2, 3)println(myList[1]) // 輸出: 2myList[1] = 4println(myList[1]) // 輸出: 4
}
- 調用操作符
我們可以為自定義類定義調用操作符()的行為。
class Greeter(val name: String) {operator fun invoke(greeting: String): String {return "$greeting, $name!"}
}fun main() {val greeter = Greeter("Twg")println(greeter("Hello")) // 輸出: Hello, Twg!
}
4.包含操作符
我們可以為自定義類定義包含操作符in和!in的行為。
class Range(val start: Int, val end: Int) {operator fun contains(value: Int): Boolean {return value in start..end}
}fun main() {val range = Range(1, 10)println(8 in range) // 輸出: trueprintln(18 !in range) // 輸出: true
}
以上就是在Kotlin中運算符重載的一些示例。通過運算符重載,我們可以使代碼更加簡潔和易讀。