官术网_书友最值得收藏!

Default arguments

Default values to the arguments is a nice way for an API to evolve. If we already have a function with two arguments and we need a third argument, we can make the transition easy by making use of default values to arguments. The existing code still works and, at the same time, we can invoke a function with new arguments. Default values to arguments make the API simple and expressive. 

Let's write an example to provide a default value to an argument to the function.

Consider the code for 6e_DefaultArguments.kts:

fun welcome(name: String, msg:String = "Hey") {
println("$msg $name")
}
welcome("Bob", "hello")
welcome("Berry")

In this case, we are not providing the second argument, msg, to the welcome() function. It therefore uses a default message instead. The output is as follows:

As shown in the preceding example, a default value to an argument can be specified with an = symbol in the argument declaration. In this case, if we don't pass the second argument while invoking the function, a default value will be provided.

主站蜘蛛池模板: 贞丰县| 饶阳县| 布尔津县| 东宁县| 耿马| 泽库县| 淅川县| 中超| 五莲县| 延安市| 马公市| 兴文县| 离岛区| 巴青县| 永川市| 万源市| 郎溪县| 郧西县| 瑞安市| 玉环县| 交城县| 西青区| 璧山县| 广河县| 河曲县| 册亨县| 延安市| 东光县| 庆元县| 祁门县| 韶关市| 府谷县| 双江| 富顺县| 富宁县| 龙川县| 阳春市| 德安县| 察隅县| 潼南县| 金溪县|