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

2021-08-15 14:26:09 字數 899 閱讀 9250

kotlin官網:other-type aliases

型別別名可以用來給乙個已知型別起另外乙個名字,如果有型別名字太長可以再起乙個短一些的替代。

經常用於帶泛型的類,例如集合:

typealias nodeset = set

typealias filetable = mutablemap>

給函式型別起別名:

typealias myhandler = (int, string, any) -> unit

typealias predicate= (t) -> boolean

給內部類和巢狀類起別名:

class

a class

b typealias ainner = a.inner

typealias binner = b.inner

型別別名並沒有產生新的型別,指向的還是被起名的型別。如上例typealias predicate= (t) -> boolean,在**中使用predicate,編譯器會轉換成(int) -> boolean。所以使用別名或原本型別都是可以的:

typealias predicate= (t) -> boolean

fun foo(p: predicate) = p(42)

fun main(args: array)

println(foo(f)) // prints "true"

val p: predicate=

println(listof(1, -2).filter(p)) // prints "[1]"

}

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

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

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

kotlin官網 other operator overloading kotlin支援過載運算子,運算子有對應固定名字的函式,可以定義為成員函式或者擴充套件函式,函式前加operator。表示式轉換 aa.unaryplus aa.unaryminus aa.not 編譯器的轉換步驟 注意,對於基...

kotlin學習筆記

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