LoginSignup
1
0

More than 5 years have passed since last update.

はじめに

今回久しぶりにコードを書いていて、Kotlinのwhenに出会ったので覚えがきしておきます。

KotlinのコードからJavaのコードを見たくなることは、JavaでAndroidをやってた人にとってはありそうなので、そんなときの方法はリンクつけておきます。

Kotlin覚書 - KotlinからJavaにデコードする方法

Kotlinで出てきたwhenさん

普通にActivity生成しただけですが、いきなり「when」を使われても正直スッと頭に入ってこなかったので確認してみました。

whenの入ったコード

コードです。

kotlin
    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_dashboard -> {
                message.setText(R.string.title_dashboard)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                message.setText(R.string.title_notifications)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

見た感じで雰囲気はわかります。

なので、BottomNavigationViewを選択したときのコールバックに対して処理が書かれてます。
Viewが3つ用意されているので、その3つのViewのリソースID毎に処理わけをしているようです。

つまり、Javaでいうところのswitch文みたいですね。
ではデコンパイルしてみてJavaのコードを覗いてみましょう。

java
   private final OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = (OnNavigationItemSelectedListener)(new OnNavigationItemSelectedListener() {
      public final boolean onNavigationItemSelected(@NotNull MenuItem item) {
         Intrinsics.checkParameterIsNotNull(item, "item");
         switch(item.getItemId()) {
         case 2131230821:
            ((TextView)TopActivity.this._$_findCachedViewById(id.message)).setText(2131558459);
            return true;
         case 2131230822:
         default:
            return false;
         case 2131230823:
            ((TextView)TopActivity.this._$_findCachedViewById(id.message)).setText(2131558460);
            return true;
         case 2131230824:
            ((TextView)TopActivity.this._$_findCachedViewById(id.message)).setText(2131558461);
            return true;
         }
      }
   });

やはりでしたね。

MenuItemの変数itemからgetItemIdをして、id毎の処理になってました。

whenの使い方

AndroidStudioでデコンパイルしただけだとswitchで書くのと変わらんやーん!
ってなったので、以下のサイトも参考にさせていただきました。ありがとうございました!

【Kotlin】whenでif-else

どうやらStringもいけるみたいですね。

自分で検証してみたいところですが、今回時間がなくてまだ検証コードがかけてないので、
それはまた後日アップしたいと思います!!

1
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
1
0