今天的内容是关于函数的默认参数。
首先我们写一个带有默认参数的函数:
fun swim(speed:String = "fast"){
println("swimming $speed")
}
然后我们有三种方式进行调用:
swim()
swim("slow")
swim(speed="slow")
注意,带默认参数的参数可以放在参数列表的任何位置(调用时需要按照名称传递参数):
swim(50,speed="slow")
我们在这期视频完成了一个函数:
fun shouldChangeWater(
day:String,
temperature:Int=22,
dirty:Int=20):Boolean{
return true
}
接下来就是练习环节:
这道练习题有点意思,这里就放我翻译的简版题目了。
首先题目要求是写一个函数判断能否在一个水族箱里放下鱼,有一个规则:在水族箱没有装饰的情况下,一加仑的水配一条一英寸的鱼
比如说,
一个有装饰的水族箱可以容纳小于或等于80%长度的鱼
一个没有装饰的水族箱可以容纳100%长度的鱼
一个有装饰的10加仑的水族箱可以容纳8英寸的鱼,比如4条两英寸的
一个没有装饰的10加仑的水族箱可以容纳10英寸的鱼。比如6条一英寸的和2跳2英寸的(这里原文写的是20加仑和20英寸)
然后是对函数的要求,我就直接复制了:
fitMoreFish function
Create a function that takes these arguments:
tankSize (in gallons)
currentFish (a list of Ints representing the length of each fish currently in the tank)
fishSize (the length of the new fish we want to add to the tank)
hasDecorations (true if the the tank has decorations, false if not)
You can assume that typically a tank has decorations, and that a typical fish is 2 inches long. That means you can set those values as default parameters.
要求的输出是下面这样的:
canAddFish(10.0, listOf(3,3,3)) ---> false
canAddFish(8.0, listOf(2,2,2), hasDecorations = false) ---> true
canAddFish(9.0, listOf(1,1,3), 3) ---> false
canAddFish(10.0, listOf(), 7, true) ---> true
这种编程题一般没有绝对正确或错误的答案,大家写完自己的程序之后可以和官方参考答案对比一下(不得不说参考答案真的精巧):
fun canAddFish(tankSize: Double, currentFish: List<Int>, fishSize: Int = 2, hasDecorations: Boolean = true): Boolean {
return (tankSize * if (hasDecorations) 0.8 else 1.0) >= (currentFish.sum() + fishSize)
}
下面还有一道:
Create a program that suggests an activity based on various parameters.
Start in a new file with a main function.
From main(), create a function, whatShouldIDoToday().
Let the function have three parameters.
mood: a required string parameter
weather: a string parameter that defaults to "sunny"
temperature: an Integer parameter that defaults to 24 (Celsius).
Use a when construct to return some activities based on combinations of conditions. For example:
mood == "happy" && weather == "Sunny" -> "go for a walk"
else -> "Stay home and read."
Copy/paste your finished function into REPL, and call it with combinations of arguments. For example:
whatShouldIDoToday("sad")
> Stay home and read.
Note: Keep your work as you will do more with this code in the next practice.
那么官方的参考答案是(一种when语句的新用法):
fun main(args: Array<String>) {
println(whatShouldIDoToday("happy"))
}
fun whatShouldIDoToday(mood: String, weather: String = "sunny", temperature: Int = 24) : String {
return when {
mood == "happy" && weather == "sunny" -> "go for a walk"
else -> "Stay home and read."
}
}