- kotlin 在定义函数的时候,参数是可以带着默认值的,如下
/*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
-
kotlin 函数默认参数的传参顺序要注意:https://www.jianshu.com/p/32424d267412
-
最后,以上的例子只是kotlin中一个三个参数的function,那如果一个funciton有更多的参数,java要 写多少构造方法才能实现和kotlin同等的调用结果呢?
网友评论