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 標籤
Break 與Continue 標籤
記得 @的位置,一個@放後面一個@放前面.
他就會直接跳出loop,可以省去break兩次的判斷.
留言
張貼留言