5
4

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 3 years have passed since last update.

【Kotlin】`!` は使うな!

Last updated at Posted at 2020-06-20

2行でいうと

! は読みにくい。
代わりに .not() を使おう。

! は読みにくい

例えば Double 型の変数 number の値が NaN でないかどうかを判定する場合を考える。

普通は次のように書くだろう。

if (!number.isNaN()) {
    TODO()
}

しかし ! は視認性が悪いし

if (!illegal) {
    TODO()
}

メソッドチェーンで処理が前から後ろに流れるように書いても
最後に処理が先頭に戻ることになり読みにくい。

if (!number.roundToInt().toString(16).contains('0')) {
    TODO()
}

.not() を使おう

Kotlin では演算子をオーバーロードすることができる。
! 演算子をオーバーロードする場合であれば次のように
not オペレーター関数をオーバーロードするというような書き方になる。

!演算子をオーバーロードする例
object Left
object Right
operator fun Left.not() = Right
operator fun Right.not() = Left

オペレーター関数は普通の関数と同じように呼び出すことができる。
それを使うとこのように書くことができる。

if (number.isNaN().not()) {
    TODO()
}

これで視認性もよく、流れるように読み書きできるようになった。

おまけ

次のような関数を定義しておくと

fun not(boolean: Boolean): Boolean =
    boolean.not()

inline fun not(predicate: () -> Boolean): Boolean =
    predicate().not()

inline fun <T> T.not(predicate: T.() -> Boolean): Boolean =
    predicate().not()

次のような書き方ができる。

if (not(number.isNaN())) {
    TODO()
}

if (not { number.isNaN() }) {
    TODO()
}

if (number.not { isNaN() }) {
    TODO()
}

場合によってはこの方が読みやすいこともあるだろう。

/以上

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?