在这个示例中,我不了解如何从Android documentation中为INSTANCE变量分配值
MySingleton constructor(context: Context) {
companion object {
@Volatile
private var INSTANCE: MySingleton? = null
fun getInstance(context: Context) =
INSTANCE ?: synchronized(this) {
INSTANCE ?: MySingleton(context)
}
}
我了解代码的作用。我只是不了解语法。似乎那里应该有一些平等的迹象。
最佳答案
其实...
It seems like there should be some equal signs in there instead of colons.
你是绝对正确的!这个例子是错误的!它将转换为以下Java代码:
private static volatile MySingleton INSTANCE;
public static MySingleton getInstance(Context context) {
if(INSTANCE != null) {
return INSTANCE;
} else {
synchronized(this) {
if(INSTANCE != null) {
return INSTANCE;
}
return new MySingleton(context);
}
}
}
如您所见,INSTANCE变量实际上从未设置。 -_-
它应该是:
class MySingleton(context: Context) {
companion object {
@Volatile @JvmField private var INSTANCE: MySingleton? = null
fun getInstance(context: Context) =
INSTANCE ?: synchronized(this) {
INSTANCE ?: MySingleton(context).also { INSTANCE = it }
}
}
}
关于syntax - 需要帮助来了解android.volley.requestQueue文档示例的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51546056/