Kotlin 運算符重載

kotlin運算符重載的範圍

java是不支持任何運算符重載的,可是kotlin支持,這裏要注意的是kotlin支持的運算符重載也是有限的,不像c++ 的重載那麼強大靈活。html

能夠去官網查看支持哪些運算符的重載java

其中出鏡率最高的幾個,咱們總結一下c++

==與equals+與plusin與contains[]與get>與compareto()與invoke安全

重載運算符的實例

定義一個複數類bash

//複數
class Complex(var real: Double, var image: Double) {
    override fun toString(): String {
        return "$real+${image}i"
    }
}
複製代碼

而後咱們對他進行一些運算符重載。ide

operator fun Complex.plus(other: Complex): Complex {
    return Complex(this.real + other.real, this.image + other.image)
}

operator fun Complex.plus(other: Double): Complex {
    return Complex(this.real + other, this.image)
}

operator fun Complex.plus(other: Int): Complex {
    return Complex(this.real + other, this.image)
}

operator fun Complex.minus(real: Double): Complex {
    return Complex(this.real - real, this.image)
}

//0 返回虛部 1實部
operator fun Complex.get(index:Int):Double{
    return when(index){
        0 -> this.real
        1 -> this.image
        else -> throw IndexOutOfBoundsException()
    }
}
複製代碼

而後看看他的使用ui

fun main() {
    val c = Complex(1.0, 2.0)
    println(c)

    val c1=Complex(3.0,4.0)
    val c2=Complex(2.0,2.0)

    println(c1+c2)
    println(c1+3)
    println(c1+2.0)
    println(c1-1.0)
    println(c1[1])
    println(c1[0])

}
複製代碼

結果this

經過這個例子 你應該能看出來,kotlin的運算符重載最大的做用就是增長這門語言的表達力spa

中綴表達式

看個最簡單的例子,應該有人知道 to的做用吧。 3d

那這個to 本質上是啥?

實際上他就等價於

println(2.to(3))

複製代碼

咱們看一下源碼:

這個infix 關鍵字 就是告訴編譯器 能夠 用 2 to 3 的這種簡寫方式了。

好比 咱們想 逆序一個字符串

//index 爲分割線  分割一個字符串
infix fun String.rotate(count: Int): String {
    val index = count % length
    return this.substring(index) + this.substring(0, index)
}

複製代碼
fun main() {

   println("helloworld" rotate 5)
    println("helloworld".rotate(5))

}
複製代碼

看下結果;

和 to的 寫法 其實就是同樣的了。 不加infix的話 就不能夠用簡寫的方式了

中綴表達式 在 kotlin dsl中 很常見,必定要掌握。

kotlin 中 空安全要額外注意的地方

kotlin中的 空類型繼承關係

智能類型轉換的建議寫法

相關文章
相關標籤/搜索