函数
在kotlin中 使用fun关键字声明一个函数
fun double(x:Int):Int{
return 2*x;
}
函数参数
有默认值的函数,可减少重载
fun read(
b:ByteArray,
off:Int =0,
len:Int = b.size
){}
覆写具有默认值的函数时,默认参数的值一定要从方法签名中省略
open class A {
open fun foo(i: Int = 10) { /*...*/ }
}
class B : A() {
override fun foo(i: Int) { /*...*/ } // No default value is allowed.
}
如果一个默认参数在非默认参数的前面,需要在调用方法传入参数时指定参数的名字
fun foo(
bar: Int = 0,
baz: Int,
) { /*...*/ }
foo(baz = 1) // The default value bar = 0 is used
如果在最后一个默认参数后面是一个lambda,可以通过使用命名参数或者括号外
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函数
Unit代表返回一个没有用的值,不必显示返回
fun printHello(name: String?): Unit {
if (name != null)
println("Hello $name")
else
println("Hi there!")
// `return Unit` or `return` is optional
}
可变参数Varargs
中缀表达式Infix notation
中缀表达式必须满足下列的条件
- 必须是成员函数或者是扩展函数
- 必须只有一个参数
- 参数不能是可变参数,并且没有默认值
infix fun Int.shl(x: Int): Int { ... }
// calling the function using the infix notation
1 shl 2
// is the same as
1.shl(2)
中缀表达式的优先级要低于算数表达式 ,但高于&& || is in操作符
本地函数,在函数内部定义的函数
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())
}
范型函数
在函数名前,用一个尖括号表识范型
fun <T> singletonList(item: T): List<T> { /*...*/ }
尾递归函数
对于一些循环函数,可以使用递归来代替,并且没有stack overflow风险。当一个函数被标识为tailrec ,编译器会进行优化,以达到更搞得效率。
注意不能在try/catch/finally中调用。
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))
网友评论