LoginSignup
6
3

More than 5 years have passed since last update.

null安全な言語の場合、左辺がnullableならば==trueという比較は有用

Last updated at Posted at 2018-02-20

Javaではif (flag == true)というコードを書いてはいけない を読んで、言語によってはこれが有用なケースもあるよというのを紹介します。

kotlinやswiftでスマホアプリを作っていると、nullになる可能性があるBooleanがしばしば登場します。
この場合、上の記事のように書くためには事前にnullでないことを証明する必要があります。

kotlin

val b: Boolean? = true

if (b != null) {
  if (b) {
    ...
  }
}

swift

let b: Bool? = true

if let notNullB = b {
  if notNullB {
    ...
  }
}

このBooleanをただの条件分岐として使うだけの用途の場合は、trueかそれ以外という形にするとすっきりと書けます。

kotlin

val b: Boolean? = true

if (b == true) {
  // bがtrueの時だけ実行される
}

swift

let b: Bool? = true

if b == true {
  // bがtrueの時だけ実行される
}

この場合、elseになる条件はbがnullまたはfalseとなります。

6
3
1

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
6
3