3、函数
这一期的视频主要内容是Kotlin中的函数
我们从这一期开始需要用到源文件,在IDEA中新建一个Kotlin文件的步骤如下:
- 找到项目视图中的src文件夹
- 在src文件夹上右键->New->Kotlin File/Class
- 填写文件信息并确认
要运行Kotlin文件,文件中必须要有一个主函数:
fun main(args:Array<String>){
}
注意,Kotlin的所有函数都会返回一些东西(即使没有return语句),类似主函数这样的函数会返回一个type unit来代表没有值。type unit就是Kotlin认为的没有值,当一个函数返回type unit,那么就没必要写return
接下来是一个练习(必须要做,以后还会用到):
- Create a new Kotlin file.
- Copy and paste the main() function from Hello World into the file.
- Create a new function, dayOfWeek().
- In the body of the function, print "What day is it today?"
- Call dayOfWeek() from main().
- Run your program.
官方答案是:
fun main(args: Array<String>) {
dayOfWeek()
}
fun dayOfWeek() {
println("What day is it today?")
}
下面继续练习:
In the body of the dayOfWeek() function, answer the question by printing the current day of the week.
这里有一系列提示:
- You can use Java libraries (java.util) from Kotlin. For example, to get the day of the week:
- Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
- Type in the code, then press Option + Enter in Mac, or Alt + Enter in Windows, over the red Calendar class to import the library.
- Use a when statement to print a string depending on the day. Sunday is the first day of the week.
官方答案是:
fun dayOfWeek() {
println("What day is it today?")
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
println( when (day) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
7 -> "Saturday"
else -> "Time has stopped"
})
}
接下来我们要学习的是命令行参数。
首先在IDEA中打开run->edit configuration,在program arguments中填入kotlin,之后确认
然后我们需要在程序中使用这个参数,将main函数修改如下:
fun main(args:Array<String>){
println("我爱你~${args[0]}")
val isUnit = println("This is an expression")
println(isUnit)
val temperature = 10
val isHot = if(temperature>50) true else false
println(isHot)
val message = "You are ${if(temperature>50) "fried" else "safe"} fish"
println(message)
}
上面的例子还说明了,在${}中可以使用表达式
那么再做一些练习题~
Create a main() function that takes an argument representing the time in 24-hour format (values between and including 0 -> 23).
In the main() function, check if the time is before midday (<12), then print "Good morning, Kotlin"; otherwise, print "Good night, Kotlin".
注意:
Remember that all main() function arguments are Strings, so you will have to convert this argument to an Int before you can apply the check.
高级一点:
Try to use Kotlin's string templates to do this in 1 line.
正确答案是(包含两种写法):
fun main(args:Array<String>){
if (args[0].toInt()<12) println("Good morning Kotlin")
else println("Good night Kotlin")
// 一行表示
println("Good ${if (args[0].toInt()<12) "morning" else "night"},Kotlin")
}