Kotlin - 函式基礎
- 函式參數是唯讀的
範例:Private 函式(預設是 public)
package examples
fun main() {
val i = 100
printS(i)
println(publicPrint(i))
}
fun publicPrint(i: Int):String {
return when(i) {
in 0..100 -> "0-100"
else -> "else"
}
}
private fun printS(i: Int) {
return when(i) {
in 0..100 -> println("0-100")
else -> println("else")
}
}
預設參數值
package examples
fun main() {
printNumber(50) // print 50
printNumber() // print 100
}
fun printNumber(n: Int = 100) {
println(n)
}
單行函式
package examples
fun main() {
printNumber(50) // print 50
printNumber() // print 100
}
fun printNumber(n: Int = 100) = println(n)
具名引數
package examples
fun main() {
printABC(1,2,3) // print 1,2,3
printABC(c=1, a=2, b=3) // print 2,3,1
}
fun printABC(a:Int,b:Int,c:Int) {
println("a=$a, b=$b, c=$c")
}
Unit 型別與 Nothing 型別
- Unit 型別等同於 Java 的 void
- Nothing 型別等同於 Java 裡拋出 UnSupportedException
package examples
fun main() {
val u1 : Unit = printABC(1,2,3) // print 1,2,3
val u2 : Unit = printABC(c=1, a=2, b=3) // print 2,3,1
println(u1) // Print kotlin.Unit
println(u2) // Print kotlin.Unit
notImplemented()
println("No reachable") // won't be printed
}
fun notImplemented(): Nothing = throw NotImplementedError()
fun printABC(a:Int,b:Int,c:Int) {
println("a=$a, b=$b, c=$c")
}
輸出結果
a=1, b=2, c=3
a=2, b=3, c=1
kotlin.Unit
kotlin.Unit
Exception in thread "main" kotlin.NotImplementedError: An operation is not implemented.
at examples.HelloKt.notImplemented(Hello.kt:11)
at examples.HelloKt.main(Hello.kt:8)
at examples.HelloKt.main(Hello.kt)
Process finished with exit code 1
反引號函式名稱
- 這是為了解決 Java 與 Kotlin 保留字衝突的方案
- 寫單元測試的時候很好用
package examples
fun main() {
`this is a book test`()
}
fun `this is a book test`() {
println("assert this is a book")
}
檔案層級變數
examples/MyNumber.kt
package examples
const val MAX = 10000
examples/Hello.ky
package examples
// const val MAX = 30 // can't declare MAX twice under the same package
fun main() {
println(MAX) // don't need specify
}
example2/MyNumber2.kt
package example2
const val MAX = 4000 // can use same name as examples/MyNumber.kt
const val MAX2 = examples.MAX // can reference another packages constant