美文网首页
kotlin函数

kotlin函数

作者: 今天也要努力呀y | 来源:发表于2020-03-27 19:15 被阅读0次

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
}

相关文章

网友评论

      本文标题:kotlin函数

      本文链接:https://www.haomeiwen.com/subject/hpdruhtx.html