如果我们将成员变量定义为
private var foo: Foo? = null当我们调用带有参数的方法(初始化Foo时需要)时,我们想要初始化它,有没有比这更好的方法呢?
fun generateFoo(bar: Bar): Foo { var localFoo = foo if (localFoo == null) { localFoo = Foo(bar) foo = localFoo } return localFoo }我正在考虑避免所有变量赋值。
编辑:这里的版本略短,但仍不理想
fun generateFoo(bar: Bar): Foo { var localFoo = foo ?: Foo(bar) foo = localFoo return localFoo }If we have a member variable defined as
private var foo: Foo? = nulland 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 }最满意答案
这是安全的,除非你有多个线程命中你的类:
fun generateFoo(bar: Bar): Foo { if (foo == null) { foo = Foo(bar) } return foo!! }但是如果你愿意,你可以做这样的事情 - 取决于你是否认为这比你已经拥有的更长版本更具可读性:
fun generateFoo(bar: Bar) = foo ?: Foo(bar).also { foo = it }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 }懒惰初始化可空成员(Lazy initialization of nullable member)如果我们将成员变量定义为
private var foo: Foo? = null当我们调用带有参数的方法(初始化Foo时需要)时,我们想要初始化它,有没有比这更好的方法呢?
fun generateFoo(bar: Bar): Foo { var localFoo = foo if (localFoo == null) { localFoo = Foo(bar) foo = localFoo } return localFoo }我正在考虑避免所有变量赋值。
编辑:这里的版本略短,但仍不理想
fun generateFoo(bar: Bar): Foo { var localFoo = foo ?: Foo(bar) foo = localFoo return localFoo }If we have a member variable defined as
private var foo: Foo? = nulland 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 }最满意答案
这是安全的,除非你有多个线程命中你的类:
fun generateFoo(bar: Bar): Foo { if (foo == null) { foo = Foo(bar) } return foo!! }但是如果你愿意,你可以做这样的事情 - 取决于你是否认为这比你已经拥有的更长版本更具可读性:
fun generateFoo(bar: Bar) = foo ?: Foo(bar).also { foo = it }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 }
发布评论