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

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.

主站蜘蛛池模板: 南皮县| 江都市| 临沂市| 石门县| 沁阳市| 沂南县| 昆山市| 玉溪市| 师宗县| 太康县| 霍邱县| 九龙县| 翁牛特旗| 精河县| 胶州市| 博湖县| 双峰县| 繁峙县| 双桥区| 民和| 红安县| 靖西县| 吉木乃县| 上栗县| 清流县| 海阳市| 甘泉县| 嘉善县| 迁西县| 沛县| 会昌县| 犍为县| 镇宁| 龙游县| 江西省| 宾阳县| 象州县| 阿巴嘎旗| 澎湖县| 孟连| 海原县|