Kotlin之字面函式和函式表示式
阿新 • • 發佈:2019-01-09
這一節涉及的東西比較雜,各種函式和表示式,零零散散
package net.edaibu.kotlintest.FunctionAndLambda /** * @author geqipeng * * @date 2017/6/1 * * @time 16:39 */ //字面函式和函式表示式 //字面函式 fun findBigOne(a: Int, b: Int): Boolean { return a > b } //函式文字語法 val sum1 = { x: Int, y: Int -> x + y } //寫法二 val sum2: (Int, Int) -> Int = { x, y -> x + y } //函式表示式 fun getSum(x: Int, y: Int): Int = x + y //函式表示式2 fun getSum2(x: Int, y: Int): Int { return x + y } //函式表示式擴充套件 var sum = fun Int.(other: Int): Int = this + other //資料型別智慧轉換 fun transfer(x: Any) { if (x is String) { println(x.length) } } //函式引用 fun testQuote(num: Int) = num % 2 != 0 //屬性引用 var xx = 1 //擴充套件屬性 val String.lastChar:Char get() = 'k' fun main(args: Array<String>) { println(getSum(10, 20)) //30 println(getSum2(10, 20)) //30 println("range_________________________") //range for (i in 1..5) { println(i) //12345 } println("if判斷____________________________") var i = 5 if (i in 1..5) { println(i) //5 } println("downto______________________________") //逆序輸出 downto for (i in 4 downTo 2) { println(i) //432 } println("reverse————————————————————————————————————————") for (i in (1..5).reversed()) println(i) //54321 println("is 表示式————————————————————————————————————————————") //is表示式 if ("哈哈" is String) { println("is string") //is string } println("智慧轉換——————————————————————————————————————") println(transfer("hello kotlin")) //12 println("when表示式——————————————————————————————————") var x: Any = 100 when (x) { is Int -> print(x) //100 is String -> print(x.length) } println("運算子過載————————————————————————————————————————————————") //運算子過載 var a = 10 var b = 20 //加 val c = a.plus(b) //減 val d = a.minus(b) //乘 val e = a.times(b) //除 val f = a.div(b) //取餘 val g = a.mod(b) print("__c=" + c + "_d=" + d + "_e=" + e + "_f=" + f + "_g=" + g) //__c=30_d=-10_e=200_f=0_g=10 //空安全 var n: String? = "hahaha" n = null //採用?符號進行為空判斷即 n不為空才將n的長度賦值給m val m = n?.length println(m) //函式引用 使用符號::來引用方法 println("函式引用——————————————————————————————————") var list1 = listOf(1, 2, 3, 4) println(list1.filter(::testQuote)) // [1, 3] println("屬性引用______________________________") println(::xx.get()) //1 ::xx.set(2) //通過set方法來進行賦值 println(::xx.get()) //2 println("擴充套件屬性_______________________________") println(String::lastChar.get("kotlin")) // k }