kotlin 函数默认参数

2018-11-16  本文已影响0人  toExploreFuture
/*kotlin 函数默认参数*/
object KotlinFunctionDefaultParamValue {
    @JvmStatic
    fun show(name : String = "to-explore-future",gender : Boolean = true,height : Int = 120){
        println("name = $name , isMan = $gender , height = $height")
    }
}

如果调用的时候,不传参数,系统使用参数的默认值

fun aboutKotlinDefaultParamValue(){
    KotlinFunctionDefaultParamValue.show()
    KotlinFunctionDefaultParamValue.show("lucy")
    KotlinFunctionDefaultParamValue.show("zq",true)
    KotlinFunctionDefaultParamValue.show("tom",true,180)
}

输出结果

name = to-explore-future , isMan = true , height = 120
name = lucy , isMan = true , height = 120
name = zq , isMan = true , height = 120
name = tom , isMan = true , height = 180

比java强在什么地方:省去写重载方法

看看同样的输出,java要怎么实现

public class JavaOverLoadedMethod {

    public static void show(){
        show("to-explore-future");
    }

    public static void show(String name){
        show(name.isEmpty() ? "to-explore-future" : name,true);
    }

    public static void show(String name, boolean isMan) {
        show(name.isEmpty() ? "to-explore-future":name,isMan,180);
    }

    public static void show(String name, boolean isMan, int height) {
        System.out.println("name = " + name + ", isMan = " + isMan + ", height = " + height);
    }
}

java调用,以及输出结果

fun aboutKotlinDefaultParamValue(){
    JavaOverLoadedMethod.show()
    JavaOverLoadedMethod.show("Lucy")
    JavaOverLoadedMethod.show("zq", true)
    JavaOverLoadedMethod.show("tom", true, 180)
}

name = to-explore-future, isMan = true, height = 180
name = Lucy, isMan = true, height = 180
name = zq, isMan = true, height = 180
name = tom, isMan = true, height = 180

上一篇下一篇

猜你喜欢

热点阅读