Kotlin: function
function default value
參數可以宣告 default 值
fun connectToDb(hostname: String = "localhost",
username: String = "mysql",
password:String = "secret") {
}
這樣不用特別定義多個 functions 給不同參數的狀況.
而可以省略呼叫用 default 值的參數, 如下:
connectToDb("mycomputer","root")
----
Extension Functions
class Greeter {
fun hello(msg: String) = "Hello, $msg"
fun hi(msg: String) = "Hi, $msg"
fun terminatorify(msg: String) = "$msg, I'll be back"
}
fun main(args: Array<String>) {
val name = "Simpson"
val g = Greeter();
println(g.hello(name))
println(g.hi(name))
println(g.terminatorify(name))
}
Hello, Simpson
Hi, Simpson
Simpson, I'll be back
----
infix
class Person(val name : String) {
fun say(message: String) = println("$name is saying $message")
}
fun main(args: Array<String>) {
val Simpson = Person("Simpson")
Simpson.say("Hello World!")
}
Simpson is saying Hello World!
像這函式只有一個參數, 可以改用 infix
class Person(val name : String) {
infix fun say(message: String) = println("$name is saying $message")
}
這樣可以用底下這方式呼叫:
fun main(args: Array<String>) {
val Simpson = Person("Simpson")
Simpson say "Hello World!"
}
---
operator overloading
留言
張貼留言