0
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 1 year has passed since last update.

KotlinでNULLではない場合に処理をしたい時

Posted at

null安全な言語であるKotlinで、Boolean?型の変数が

  • nullじゃなかったら処理をする
  • nullだったら処理をしない
    という実装がしたかった。
    その際の個人メモ。

考えられる実装方法

その1 if文を使う

    var a :Boolean? = null
    
    if (a == null) { // ←vaの場合はヌルポで落ちるけど、Kotlnなら大丈夫
        // ここの処理が通る
        println("nullなら通る")
        println("true、falseなら通らない")
    }
実行結果

2024-05-21_20h08_22.png

参考サイト

備考

  • nullを許容する?の位置に注意
  • withだとBoolean!型からBoolean型に変換してくれない
実行結果
nullを許容する?の位置に注意
fun main() {
    println("★main関数スタート★")
    var a :Boolean? = null
    
    a?.let { // ←「a?」になっていることで、ここでnullが弾かれて、ラムダ式の中で「a」(「it」)はBoolean型になる
      println("aがnullじゃなければ、ここを通る")
      if (it) { // itはa
          println("aがtrueなら、ここを通る")
      }
    }
    
    a.let { // ←「a」になっていることで、nullでもラムダ式の中の処理が実行されて、「a」(「it」)はBoolean!型になる
      println("aがnullじゃなければ、ここを通る")
      if (it) { // itはa
          println("aがtrueなら、ここを通る")
      }
    }
    println("★main関数終了★")
}

2024-05-21_23h14_13.png

withだとBoolean!型からBoolean型に変換してくれない
fun main() {
    println("★main関数スタート★")
    var a :Boolean? = null

    with(a) {
        if (this) { // withだとBoolean!型からBoolean型に変換してくれない
          println("aがtrueなら、ここを通る")
      }
    }
    println("★main関数終了★")
}

2024-05-21_23h22_27.png

その2 スコープ関数を使う

    var a :Boolean? = null
    
    a?.let { 
      println("aがnullじゃなければ、ここを通る")
      if (it) { // itはa
          println("aがtrueなら、ここを通る")
      }
    }
実行結果

2024-05-21_23h00_56.png

参考サイト

その他参考サイト

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