Kotlin學習筆記5 7 其他 運算子過載

2021-08-15 13:23:43 字數 3116 閱讀 7787

kotlin官網:other-operator overloading

kotlin支援過載運算子,運算子有對應固定名字的函式,可以定義為成員函式或者擴充套件函式,函式前加operator

表示式轉換

+aa.unaryplus()

-aa.unaryminus()

!aa.not()

編譯器的轉換步驟:

注意,對於基本型別有特殊優化,沒有呼叫相應函式的效能損耗。

舉個例子:

kotlin官網:other-operator overloading

kotlin支援過載運算子,運算子有對應固定名字的函式,可以定義為成員函式或者擴充套件函式,函式前加operator

表示式轉換

+aa.unaryplus()

-aa.unaryminus()

!aa.not()

對於**內表示式的編譯步驟:

注意,對於基本型別有特殊優化,沒有呼叫相應函式的效能損耗。

舉個例子:

data class point(val x: int, val y: int)

operator fun point.unaryminus() = point(-x, -y)

val point = point(10, 20)

println(-point) // prints "(-10, -20)"

表示式

轉換a++

a.inc() + see below

a–a.dec() + see below

inc()函式或dec()函式需要返回乙個值,賦值給呼叫++或–運算子的變數。對於呼叫者,表示式的值和原物件相同。

對於後置運算子,以a++為例,編譯器處理如下:

計算步驟:

a--的原理和步驟和a++完全相同。

對於前置運算子++a和–a運算步驟和前置的相似,區別在於:

表示式轉換

a + b

a.plus(b)

a - b

a.minus(b)

a * b

a.times(b)

a / b

a.div(b)

a % b

a.rem(b), a.mod(b) (deprecated)

a..b

a.rangeto(b)

編譯器只是簡單轉換成右側,沒有特殊處理。

其中,rem是kotlin1.1中新增的,kotlin1.0使用mod,在1.1中被廢棄。

舉個例子,counter類過載+:

data class counter

(val

dayindex: int)

}

表示式

轉換a in b

b.contains(a)

a !in b

!b.contains(a)

in和!in與其他運算子函式的區別是函式的接收者和引數順序是顛倒的。

表示式轉換

a[i]

a.get(i)

a[i, j]

a.get(i, j)

a[i_1, …, i_n]

a.get(i_1, …, i_n)

a[i] = b

a.set(i, b)

a[i, j] = b

a.set(i, j, b)

a[i_1, …, i_n] = b

a.set(i_1, …, i_n, b)

方括號轉換成對應下標的get和set函式。

表示式轉換

a()a.invoke()

a(i)

a.invoke(i)

a(i, j)

a.invoke(i, j)

a(i_1, …, i_n)

a.invoke(i_1, …, i_n)

括號轉換成invoke函式的引數。

表示式轉換

a += b

a.plusassign(b)

a -= b

a.minusassign(b)

a *= b

a.timesassign(b)

a /= b

a.divassign(b)

a %= b

a.remassign(b), a.modassign(b) (deprecated)

對於賦值運算的編譯器執行步驟,以a += b為例:

生成**`a = a + b,a + b的返回值必須為a的型別的子類。

kotlin中,賦值運算不是表示式。

表示式轉換

a == b

a?.equals(b) ?: (b === null)

a != b

!(a?.equals(b) ?: (b === null))

注意:===!==不允許過載。

對於null有特殊處理,對於null == null永遠為true,對於x == null,如果x為非空型別,用永遠為false,不會執行x.equals()

表示式轉換

a > b

a.compareto(b) > 0

a < b

a.compareto(b) < 0

a >= b

a.compareto(b) >= 0

a <= b

a.compareto(b) <= 0

比較運算子轉換成compareto函式,要求返回int型。

詳見3-13委託屬性

表示式轉換

a > b

a.compareto(b) > 0

a < b

a.compareto(b) < 0

a >= b

a.compareto(b) >= 0

a <= b

a.compareto(b) <= 0

比較運算子轉換成compareto函式,要求返回int型。

詳見3-13委託屬性

詳見4-1函式

Kotlin學習筆記5 1 其他 解構宣告

kotlin官網 other destructuring declarations 解構宣告可以方便地將乙個物件分解成多個變數 val name,age person println name println age 上例中,解構宣告會編譯成 val name person.component1 v...

Kotlin學習筆記5 13 其他 型別別名

kotlin官網 other type aliases 型別別名可以用來給乙個已知型別起另外乙個名字,如果有型別名字太長可以再起乙個短一些的替代。經常用於帶泛型的類,例如集合 typealias nodeset set typealias filetable mutablemap 給函式型別起別名 ...

kotlin學習筆記

屬性委託在單獨一頁中講 屬性委託。委託模式已經證明是實現繼承的乙個很好的替代方式,而 kotlin 可以零樣板 地原生支援它。derived類可以通過將其所有公有成員都委託給指定物件來實現乙個介面base inte ce base class baseimpl val x int base clas...