[Android App 開發筆記] #從零開始 #D05: Kotlin Functions, Part-2

 

[Android App 開發筆記] #從零開始 #D05: Kotlin Functions, Part-2

# Android App 開發

# Reference: Kotlin Bootcamp for Programmers (Link), Lesson 3: Kotlin Functions (Link)

# Kotlin docs (所有不會的程式碼都可以看這裡: Link)


[Learn more functions]

randomDay(): pick a random day from an array and return it
nextInt(): takes an integer limit

fun feedTheFish(){
    val day = randomDay()
    val food = "pellets"
    println("Today is $day and the fish eat $food")
}
fun main(args: Array<String>){
    feedTheFish()
}
fun randomDay(): String{
    val week = arrayOf("Mon.", "Tue.", "Wed.", "Thur.",
               "Fri.", "Sat.", "Sun.")
    return week [Random ().nextInt(week.size)]
}


*******************

random() 和 nextInt() 都defined in java.util.* → 一開始就要 import

*******************

import java.util.*


[完整版本 CODE]

import java.util.*    // required import

fun randomDay() : String {
    val week = arrayOf ("Monday", "Tuesday", "Wednesday", "Thursday",
        "Friday", "Saturday", "Sunday")
    return week[Random().nextInt(week.size)]
}

fun fishFood (day : String) : String {
    return when (day) {
        "Monday" -> "flakes"
        "Wednesday" -> "redworms"
        "Thursday" -> "granules"
        "Friday" -> "mosquitoes"
        "Sunday" -> "plankton"
        else -> "nothing"
    }
}

fun feedTheFish() {
    val day = randomDay()
    val food = fishFood(day)
    println ("Today is $day and the fish eat $food")
}

fun main(args: Array<String>) {
    feedTheFish()
}


→ 棒棒 :)


[Default values and compact functions]

關於原始參數設定

fun run (speed: String = "fast") { /* 一個叫做 run 的函數, 用一個 "String" 的參數, 參數名字叫做: speed, 初始參數 default = "fast" */
    println("running $speed") /*$speed 顯示 speed 的內容 content */
}
// 接著從 main () 去 call 這些函數
run() // uses default speed
run("slow") // positional argument
run(speed="turtle-like") // named parameter


[加入更多參數]

假如我們要決定要不要出去玩 (day 的部分, 利用前面介紹過的 function)

fun SatShouldGoOut? (day: String, temperature: Int = 26, tired: Int = 60): Boolean {
    return when {
        temperature > 28 -> true
        tired < 70 -> true
        day == "Sat." ->  true
        else -> false
    }
}

[簡單的 Filter]

Filter 的功能: 取出部分的 List on some condition
val names = listOf("Brain", "Mark", "Mandy", "Kevin")
fun main(){
    println (decorations.filter {it[0] == 'p'} /* it 指的是 each items as the filter 
loops through → 如果是 true → the item included */
}
簡單的做 Filter

Photo by Louis Tsai on Unsplah


💭 Murmur time 💭 

今天不 mur., 歡迎討論

By Mark, 馬克

💬 E-mail: mata.assembled@gmail.com


0 Comments