【发布时间】:2019-12-10 22:42:06
【问题描述】:
Kotlin ?.let 线程安全吗?
假设a 变量可以在不同的线程中更改。
使用a?.let { /* */ } 线程安全吗?如果它等于if (a != null) { block() },会不会在if 中不为空而在block 中已经为空?
【问题讨论】:
-
我想如果让这个操作线程安全就太过分了
-
a在块执行时可以为空,但it不能。 IE。相当于val copy = a; if (copy != null) { block(copy) } -
@4ntoine 当 Kotlin 编译器智能地将可空类型转换为不可空类型时,您可以确定它确实是非空的。如果代码不是线程安全的,编译器会给你一个编译器错误(就像你这样做
if (a != null) { a.someFunction() }) -
它会给你的编译器错误是这样的(如果
a是Int?类型):Smart cast to 'Int' is impossible, because 'a' is a mutable property that could have been changed by this time
标签: multithreading kotlin let thread-synchronization