Reputation: 29290
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
}
Upvotes: 1
Views: 377
Reputation: 89588
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 }
Upvotes: 3