Kotlin - Functions Basic

  • Function parameter is read-only

Ex. Private function (Default is 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")
    }
}

Default parameter value
package examples

fun main() {
    printNumber(50) // print 50
    printNumber() // print 100
}

fun printNumber(n: Int = 100) {
    println(n)
}

One line function
package examples

fun main() {
    printNumber(50) // print 50
    printNumber() // print 100
}

fun printNumber(n: Int = 100) = println(n)

Named argument
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 type and Nothing type
  • Unit type is same as void in Java
  • Nothing type is same as throwing UnSupportedException in Java
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")
}
Output
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

Backticks function name
  • It's for Java and Kotlin reserved words conflict solution
  • It's useful when writing unit test code
package examples

fun main() {
    `this is a book test`()
}

fun `this is a book test`() {
    println("assert this is a book")
}

File-level variable
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


沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...