iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 7
0
Mobile Development

老姐好像要用 Kotlin 寫專案,能撐30天嗎?系列 第 7

製造貓貓的第七天:人人愛 Kotlin Extension

「喵先生真的把桌上的玩偶都帶回去了呢。」「是呀,難得可以看到他的桌面。」「難得的是可以看到他天黑前下班吧!」今天我倆慢了喵先生一步,正好聽到其他人的閒談。

「小公司的優點就是關係比較親密呢。」老姐確認過東西都收好後,提包踏出辦公室,我也迅速跟上。

「對了,你昨天用 filter 實作奇數偶數,可不可以改用 step ?還有我試著倒過來用 10..0 結果被 IDE 提醒是空的叫我改用 downTo ,感覺好像被 IDE 嘲笑了⋯⋯。」

https://ithelp.ithome.com.tw/upload/images/20200916/20129197YUlE9gI57Q.png

            for (i in 0..10 step 2) { //偶數
                print(i.toString())
            }
            for (i in 1..10 step 2) { //奇數
                print(i.toString())
            }
            for (i in 9 downTo 1 step 2) { //奇數
                print(i.toString())
            }

「那是因為 .. 其實是 operator rangeTo 的縮寫啦,所以還是得符合 rangeTo 函式的規則,結束數字要大於開始數字。就像字串相加的可以直接用 + 但其實是用到 operator plus 」

0..10 // 0.rangeTo(10)

https://ithelp.ithome.com.tw/upload/images/20200916/20129197fYBhnzXQj2.png

「另外,迴圈那個有點不一樣唷,實際測試會發現:有 step 的會是 IntProgression ,沒有 step 的話會是 IntRangedownTo 也是 step 的應用,而 kotlin SDK IntProgression 沒有實作 Extension random 。」

https://ithelp.ithome.com.tw/upload/images/20200916/20129197dxkr38jIs9.png
https://ithelp.ithome.com.tw/upload/images/20200916/20129197Il939Mkqr3.png
https://ithelp.ithome.com.tw/upload/images/20200916/2012919723hq4es9v2.png
「不過有趣的是經過 filter 後之後產生的結果有實作 random 」。

https://ithelp.ithome.com.tw/upload/images/20200916/201291974dWkglH0QF.png

https://ithelp.ithome.com.tw/upload/images/20200916/201291973Q20MCSXTb.png

「當然也可以自己實作 Extension ,比如偷偷塞一個 filter 在裡面。」

//寫在最外層
private fun IntProgression.random(): Int { //格式就是 fun {被擴充的對象}.{擴充名}: 回傳值
    return this.filter { true }.random()
}

https://ithelp.ithome.com.tw/upload/images/20200916/20129197niuuaHgTFv.png

老姐驚呼:「哇,真好!之前沒有 Extension 的時候,都是寫成參數函式引用,要用的時候不只需要記得函式名和存在哪個檔案,而且管理上也超不方便,說不定團隊裡早有人寫好但我們不知道。」

private fun random(intProgression: IntProgression): Int { //黑暗時代的寫法
    return intProgression.filter { true }.random()
}

「重點是除了函式,連屬性都可以 Extension !」我乘勝追擊。

fun Application.module(testing: Boolean = false) {
    install(ContentNegotiation) {
        gson {
        }
    }
    routing {
        get("/api/cat") {
          call.respond(mapOf("message" to (0..10 step 2).firstCat))
        }
    }
}
//寫在最外層
val IntProgression.firstCat: String
  get() = first.toString() + "Cat"

https://ithelp.ithome.com.tw/upload/images/20200916/20129197u6rOdR8y7L.png

老姐放聲大笑:「哈哈哈,這個妙,明天把 Extension 部分遮住,就可以和喵先生吹牛說現在程式碼連貓咪屬性都有了。」

本次鐵人賽的作品在放進更多內容後已經成書,書名是《老姐要用Kotlin寫專案:從 Server 到 Android APP 的開發生存日記》,歡迎購買唷。https://www.tenlong.com.tw/products/9789864348978


上一篇
眺望統一的第六天:App 設計和 Kotlin range 亂數
下一篇
做出選擇的第八天:H2 資料庫,就決定是你了
系列文
老姐好像要用 Kotlin 寫專案,能撐30天嗎?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言