kotlin函数

2020-03-27  本文已影响0人  今天也要努力呀y

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
}
上一篇 下一篇

猜你喜欢

热点阅读