Kotlin (3) : when

今早去看了一下折疊式手機, 還真有點厚,但展開來之後可以取代平板.

價格有點貴,因為螢幕多了一片在摺起來的外殼,這樣也不能裝保護套, 


----------------------
Kotlin 的When 非常強, 等同取代了 java中的Switch.

最基本的用法描述如下:

when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { print("x is neither 1 nor 2") } }

----

1 when(view.visibility){
2     View.VISIBLE -> toast("visible")
3     View.INVISIBLE -> toast("invisible")
4     else -> toast("gone")
5 }

然後他可以用判斷多種結果, 代替重複的部分.

when (x) { 0, 1 -> print("x == 0 or x == 1") else -> print("otherwise") }


---

1 val res = when {
2     x in 1..10 -> "cheap"
3     s.contains("hello") -> "it's a welcome!"
4     v is ViewGroup -> "child count: ${v.getChildCount()}"
5     else -> ""
6 }

---

1 override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
2     R.id.home -> consume { navigateToHome() }
3     R.id.search -> consume { MenuItemCompat.expandActionView(item) }
4     R.id.settings -> consume { navigateToSettings() }
5     else -> super.onOptionsItemSelected(item)
6 }


不像Java需要Break, 也不需要分號;做結尾.

也省略了case 描述.

---------------

When允許 range 與 變數: ( in or !in a range or a collection:)

when (x) { in 1..10 -> print("x is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("x is outside the range") else -> print("none of the above") }

因為不需要Break,所以他規定一個條件成立後就會跳出,不會繼續下去.


----------------

可以when也可以有回傳值: // when can also be used as an expression!
val y = when(x) {
    3 -> "yes"
    8 -> "no"
    else -> "maybe"
}

實際上使用會看到大概是:

fun checkStateByMachineId(id: Int): WorkingState {
    // Do some logic
    when (id) {
        1 -> {
            val result = mutableListOf("Warthog", "Hedgehog", "Badger", "Drake")
            return WorkingState.Finished(result)
        }
        2 -> return WorkingState.ErrorHappened("Too big too eat.")
        3 -> return WorkingState.EmptyResult
        else -> return WorkingState.Working
    }
}
----




---
然後有一點很容易搞混的地方是:While 與do .. while 還是存在在Kotlin,
ps: 因為英文中 while 是when的過去式 ....

while (x > 0) { x-- } do { val y = retrieveData() } while (y != null) // y is visible here!



-----
Break 與Continue 標籤
記得 @的位置,一個@放後面一個@放前面.

Any expression in Kotlin may be marked with a label. Labels have the form of an identifier followed by the @ sign, such as abc@ or fooBar@. To label an expression, just add a label in front of it.

Now, we can qualify a break or a continue with a label:

他就會直接跳出loop,可以省去break兩次的判斷.


留言

這個網誌中的熱門文章

最爛的銀行服務-玉山銀行

SMR疊瓦式hdd致命缺陷被解決????!!!

更改google drive預設存放目錄位置Change Google Drive Default Folder Location in Windows

ios app 上架時app icon要注意事項

Mark App Design Apps - Terms and Privacy Policy (服務條款,隱私權政策)

Gmail 永久刪除大型電子郵件

app bundle and bundletool. 關於aab安裝問題

關於google play console app應用程式簽署

舊有app在Android 12 閃退問題& app Splash screens

來談談admob廣告政策違規的不好體驗