简体   繁体   中英

Lazy initialization of nullable member

If we have a member variable defined as

private var foo: Foo? = null

and we want to initialize it when we call a method with an argument (which is needed to initialize Foo), is there a better way to do it than this?

fun generateFoo(bar: Bar): Foo {
    var localFoo = foo
    if (localFoo == null) {
        localFoo = Foo(bar)
        foo = localFoo
    }
    return localFoo
}

I'm looking at avoiding all the variable assignments.

Edit: a slightly shorter version is here, but still not ideal

fun generateFoo(bar: Bar): Foo {
    var localFoo = foo ?: Foo(bar)
    foo = localFoo
    return localFoo
}

This is safe unless you have multiple threads hitting your class:

fun generateFoo(bar: Bar): Foo {
    if (foo == null) {
        foo = Foo(bar)
    }
    return foo!!
}

But if you like, you can do things like this - up to you whether you think this is more readable than the longer version you already have:

fun generateFoo(bar: Bar) = foo ?: Foo(bar).also { foo = it }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM