2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Android初挑戦シリーズ】kotlinでのswitch/caseはwhen

Last updated at Posted at 2019-03-16

こんなかんじでTwitterのクローンアプリを実装しながらAndroidの学習を進めています。
スクリーンショット 2019-03-16 10.56.24.png

whenをみかけた場所

Twitterのタブレイアウトを実現しようと思ってたのでタブレイアウトを最初にやってたらwhen文に出会いました。

MainActivity.kt
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->

        when (item.itemId) {
            R.id.navigation_home -> {
                message.setText(R.string.title_home)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_search -> {
                message.setText(R.string.title_search)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                message.setText(R.string.title_notifications)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_directmail -> {
                message.setText(R.string.title_directmail)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

どうやらAndroidではActionイベントがコールバックで取得できるっぽい。
ボトムバーが押された時に、押されたボタンにテキストを設定して選択中モードにする処理が書いてあります。
(むかーし大学でAndroid勉強した時は、イベントリスナーに登録してSwift/ObjcのDelegateっぽいので処理書いてた気がする。)

kotlinの場合

よくある switch でなく、when を使います。それに、 case G: のような記述ではなく、G ->のようにアロー演算子(?)的な書き方をします。複数行の処理を書きたいときは -> { } のように中括弧で囲むようです。default のラベルも必要ないです。(elseとして書けます)

(caseが重複しそうなのでAmazon→Microsoftにしてます)

when.kt
when (stringValue) {
    "G" -> print("Google")
    "A" -> print("Apple")
    "F" -> print("Facebook")
    "M" -> print("Microsoft")
    "GAFM" -> {
        print("Google")
        print("Apple")
        print("Facebook")
        print("Microsoft")
    }
}

swiftの場合

比較対象としてSwiftで書いてみます。swiftは基本的には条件分岐のオペランドには()が必要ないです。(つけても良い)。馴染み深い switch/case スタイルですね。複数行の処理もそのまま書けば良いだけです。 kotlinswift も、新しい言語なのでどちらもbreak は必要じゃないですね!(かってにbreak

(クセで改行してますが、case "G": print("Google") と1行でも書けます)

switch.swift

switch stringValue {
case "G":
    print("Google")
    
case "A":
    print("Apple")
    
case "F":
    print("Facebook")
    
case "M":
    print("Microsoft")

case "GAFM":
    print("Google")
    print("Apple")
    print("Facebook")
    print("Microsoft")

default:
    print("Swiftではケースを網羅した時以外はdefaultが必要です。")
}

TODO

わかったら書くリスト!

  • Androidでのテスト
  • AAC
  • LiveData
  • Fragment
  • Activity
  • ライフライクル
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?