Help us understand the problem. What is going on with this article?

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

遅延評価とは

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

lazy

https://dogwood008.github.io/kotlin-web-site-ja/docs/reference/delegated-properties.html#%E9%81%85%E5%BB%B6-lazy

  • 一度だけ値の初期化を行う
  • 値はキャッシュされ、二回目以降は最初の値を常に返す
  • readonly
val p: String by lazy {
    // 文字列を評価
}

lateinit

https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties-and-variables

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

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

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

Delegates.notNull

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.properties/-delegates/not-null.html

  • プリミティブ型に使用可能
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
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away