1.Unit相当于void,也可不加
fun main() {
printMessage("hello world")
}
fun printMessage(mess : String): Unit {
println(mess)
}
2.参数可带默认值
[log]hello world
fun main() {
printMessage("hello world")
}
fun printMessage(mess : String,prefix : String = "log"){
println("[$prefix]$mess")
}
3.表达式作为函数体
fun sum(x:Int,y:Int) = x + y
相当于
fun sum(x:Int,y:Int) :Int {
return x+y
}
4.带vararg参数的函数(可变参数)
fun main() {
printAll("abd","asd")
}
fun printAll(vararg messages : String){
for (m in messages) println(m)
}
var 可变变量
val 不可变变量
输出:20
fun main() {
print(sumWithWeight(2,3,5,weight = 2))
}
fun sumWithWeight(vararg numbers :Int,weight :Int): Int {
var result = 0
for (m in numbers){
result += m
}
return result * weight
}
网友评论