函數(shù)
在kotlin中 使用fun關(guān)鍵字聲明一個(gè)函數(shù)
fun double(x:Int):Int{
return 2*x;
}
函數(shù)參數(shù)
有默認(rèn)值的函數(shù),可減少重載
fun read(
b:ByteArray,
off:Int =0,
len:Int = b.size
){}
覆寫具有默認(rèn)值的函數(shù)時(shí),默認(rèn)參數(shù)的值一定要從方法簽名中省略
open class A {
open fun foo(i: Int = 10) { /*...*/ }
}
class B : A() {
override fun foo(i: Int) { /*...*/ } // No default value is allowed.
}
如果一個(gè)默認(rèn)參數(shù)在非默認(rèn)參數(shù)的前面,需要在調(diào)用方法傳入?yún)?shù)時(shí)指定參數(shù)的名字
fun foo(
bar: Int = 0,
baz: Int,
) { /*...*/ }
foo(baz = 1) // The default value bar = 0 is used
如果在最后一個(gè)默認(rèn)參數(shù)后面是一個(gè)lambda,可以通過使用命名參數(shù)或者括號(hào)外
fun foo(
bar: Int = 0,
baz: Int = 1,
qux: () -> Unit,
) { /*...*/ }
foo(1) { println("hello") } // Uses the default value baz = 1
foo(qux = { println("hello") }) // Uses both default values bar = 0 and baz = 1
foo { println("hello") } // Uses both default values bar = 0 and baz = 1
//輸出
hello a
bar 1 , baz 1
hello b
bar 0 , baz 1
hello c
bar 0 , baz 1
返回Unit函數(shù)
Unit代表返回一個(gè)沒有用的值,不必顯示返回
fun printHello(name: String?): Unit {
if (name != null)
println("Hello $name")
else
println("Hi there!")
// `return Unit` or `return` is optional
}
可變參數(shù)Varargs
中綴表達(dá)式Infix notation
中綴表達(dá)式必須滿足下列的條件
- 必須是成員函數(shù)或者是擴(kuò)展函數(shù)
- 必須只有一個(gè)參數(shù)
- 參數(shù)不能是可變參數(shù),并且沒有默認(rèn)值
infix fun Int.shl(x: Int): Int { ... }
// calling the function using the infix notation
1 shl 2
// is the same as
1.shl(2)
中綴表達(dá)式的優(yōu)先級(jí)要低于算數(shù)表達(dá)式 ,但高于&& || is in操作符
本地函數(shù),在函數(shù)內(nèi)部定義的函數(shù)
fun dfs(graph: Graph) {
fun dfs(current: Vertex, visited: MutableSet<Vertex>) {
if (!visited.add(current)) return
for (v in current.neighbors)
dfs(v, visited)
}
dfs(graph.vertices[0], HashSet())
}
范型函數(shù)
在函數(shù)名前,用一個(gè)尖括號(hào)表識(shí)范型
fun <T> singletonList(item: T): List<T> { /*...*/ }
尾遞歸函數(shù)
對(duì)于一些循環(huán)函數(shù),可以使用遞歸來代替,并且沒有stack overflow風(fēng)險(xiǎn)。當(dāng)一個(gè)函數(shù)被標(biāo)識(shí)為tailrec ,編譯器會(huì)進(jìn)行優(yōu)化,以達(dá)到更搞得效率。
注意不能在try/catch/finally中調(diào)用。
val eps = 1E-10 // "good enough", could be 10^-15
tailrec fun findFixPoint(x: Double = 1.0): Double =
if (Math.abs(x - Math.cos(x)) < eps) x else findFixPoint(Math.cos(x))