9
1

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

Kotlin nullable と Java Optional の変換

Last updated at Posted at 2018-05-15

nullable => Optional

Kotlin でコードを書いていると、 Java の Optional に変換する必要が出てきます。
そういった場合は Optional.ofNullable を使って Optional に変換します。
nullable でなければ Optional.of を使うこともできます。

サンプル

    class SecurityAuditorAware: AuditorAware<Long> {
        override fun getCurrentAuditor(): Optional<Long> {
            val authentication = SecurityContextHolder.getContext().authentication

            if (authentication == null || !authentication.isAuthenticated) {
                return Optional.ofNullable(null)
            }

            return Optional.ofNullable((authentication.principal as UserDetail?)?.user?.id)
        }
    }

Java から見たら Kotlin の nullable はそうでないものと同じものに見えるので、 Optional<Long?>Optional<Long>Optional<Long>?Optional<Long?>? も同じです。 サンプルにある getCurrentAuditor() の返り値の型には それらの 4パターンを使うことができます。

Optional => nullable / not-nullable

Spring 5 の リポジトリ で findById を使うと、 Optional<T> が返ってきます。
そういう場合に Kotlin に値を渡すために Optional から中身を取り出したいことがあります。

optionalValue.get() => not-nullable
optionalValue.orElse(null) => nullable

その他

Optional 型 の値にはほかにもさまざまなmethodが用意されています。

次の記事に詳しく記載されていました。
https://qiita.com/tasogarei/items/18488e450f080a7f87f3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?