LoginSignup
0
4

More than 5 years have passed since last update.

kotlinでif文の条件に代入式を使いたい

Last updated at Posted at 2018-07-20

どういうことかというと、こういうやつ↓

if (val date = arguments?.getSerializable(ARG_DATE) as LocalDate) {
    ...

結論から言うと、できません。言語仕様がそうなので、仕方ないですね。

しかし、次のようなinline funを定義すれば、似たようなことはできます。

inline fun <T, R> ifNotNull(value: T?, thenPart: (T) -> R, elsePart: () -> R): R {
    return if (value != null) {
        thenPart(value)
    } else {
        elsePart()
    }
}

これを使えば次のように書けます。

val thenOrElse = ifNotNull(arguments?.getSerializable(ARG_DATE) as? LocalDate, {
    // it => LocalDate
    "then"
}, {
    "else"
})

then/elseパートは値を返すので、普通のif-then-else式のように使えます。

elseパートがないバージョンも定義しておけばよいと思います。

inline fun <T, R> ifNotNull(value: T?, thenPart: (T) -> R): R? {
    return if (value != null) {
        thenPart(value)
    } else {
        null
    }
}
0
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
0
4