這一期的視頻主要內(nèi)容是Kotlin中的函數(shù)
我們從這一期開始需要用到源文件,在IDEA中新建一個Kotlin文件的步驟如下:
- 找到項目視圖中的src文件夾
- 在src文件夾上右鍵->New->Kotlin File/Class
- 填寫文件信息并確認
要運行Kotlin文件,文件中必須要有一個主函數(shù):
fun main(args:Array<String>){
}
注意,Kotlin的所有函數(shù)都會返回一些東西(即使沒有return語句),類似主函數(shù)這樣的函數(shù)會返回一個type unit來代表沒有值。type unit就是Kotlin認為的沒有值,當一個函數(shù)返回type unit,那么就沒必要寫return
接下來是一個練習(xí)(必須要做,以后還會用到):
- 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?")
}
下面繼續(xù)練習(xí):
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"
})
}
接下來我們要學(xué)習(xí)的是命令行參數(shù)。
首先在IDEA中打開run->edit configuration,在program arguments中填入kotlin,之后確認
然后我們需要在程序中使用這個參數(shù),將main函數(shù)修改如下:
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)
}
上面的例子還說明了,在${}中可以使用表達式
那么再做一些練習(xí)題~
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")
}