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

KotlinのNullableをScalaのOptionのように使用する。

Last updated at Posted at 2016-01-28

ScalaのOptionにはmapgetOrElseメソッドがあって、次のような便利なイディオムが書けます。

scala
val x1: Option[Int] = Some(10)
val x2: Option[Int] = None

val y1 = x1.map(_ + 10).getOrElse(0)
// -> 20
val y2 = x2.map(_ + 10).getOrElse(0)
// -> 0

これと同じようなことをKotlinのNullableでifを書かないでやりたい。

kotlinでもこう書きたい
val x1: Int? = 10
val x2: Int? = null

val y1 = x1.map {it + 10}.getOrElse { 0 } 
// -> 20
val y2 = x2.map {it + 10}.getOrElse { 0 }
// -> 0

次のようにNullableを拡張すればOKです。(forEachはおまけ)

ScalaOption.kt
package com.frontier45

/**
 * Created by du on 16/01/29.
 */

fun <T1, T2> T1?.map(f: (T1) -> T2): T2? {
    return if (this != null) {
        f(this)
    } else {
        null
    }
}

fun <T> T?.forEach(f: (T) -> Unit): Unit {
    if (this != null) {
        f(this)
    }
}

fun <T> T?.getOrElse(f: () -> T): T {
    return this ?: f()
}

getOrElseの引数にデフォルト値ではなく、引数なしの関数を渡すことでnullだった時の値として複雑なブロックも使用できるようになっているのがポイント。

val y1 = x1.map {
  cool codes
}.getOrElse { 
  awesome codes
} 

Gistはこちら。
https://gist.github.com/lucidfrontier45/8d3dddc0d8a0d232e997

(編集 2016-01-29)
頂いたコメントよりmapforEachは不要とわかりました。代わりに?.letを使用すればいいようです。
getOrElseも別名にした方がいいです。

5
4
4

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?