LoginSignup
4
6

More than 3 years have passed since last update.

kotlin 遅延評価lazy、lateinitの使用方法

Last updated at Posted at 2019-09-14

遅延評価とは

遅延評価とは、評価を遅延して行うこと。値が必要な時に、値の評価をする。

lazy

  • 一度だけ値の初期化を行う
  • 値はキャッシュされ、二回目以降は最初の値を常に返す
  • readonly

val p: String by lazy {
    // 文字列を評価
}

lateinit

  • lateinitはプリミティブ型に使えない
  • varのみ使用可能
  • nullable不可
public class MyTest {
    lateinit var subject: TestSubject

    @SetUp fun setup() {
        subject = TestSubject()
    }

    @Test fun test() {
        subject.method()  // dereference directly
    }
}

Delegates.notNull

  • プリミティブ型に使用可能
var max: Int by Delegates.notNull()

// println(max) // will fail with IllegalStateException

max = 10
println(max) // 10

遅延評価の場合と遅延評価しない場合の処理の違い

遅延評価をしない場合


fun count(): Int {
    var i = 0
    (1..5).forEach {
        println(it)
        i = i.plus(it)
    }
    return i
}

fun main(args: Array<String>) {
    //遅延評価をしない
    val x: Int = count() //count()の処理が実行される
    if(false) println(x)
}

実行結果
count()の処理が実行されている

1
2
3
4
5

遅延評価の場合


fun count(): Int {
    var i = 0
    (1..5).forEach {
        println(it)
        i = i.plus(it)
    }
    return i
}

fun main(args: Array<String>) {
    /* 遅延評価
    count()の処理が実行されない */
    val x: Int by lazy {
        count()
    }
    //trueの場合のみcount()の処理が実行される
    if(false) println(x)
}

実行結果
count()の処理が実行されていない

一度実行すると結果を保持します。 それ以降は記憶された結果が返されます。
2回目の実行はcount()を実行しない

fun count(): Int {
    var i = 0
    (1..5).forEach {
        println(it)
        i = i.plus(it)
    }
    return i
}

fun main(args: Array<String>) {
    val x: Int by lazy {
        count()
    }
    println(x)
    println(x)
}

実行結果

1
2
3
4
5
15
15
4
6
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
4
6