【问题标题】:Need help understanding syntax of android.volley.requestQueue documentation example需要帮助理解 android.volley.requestQueue 文档示例的语法
【发布时间】:2018-07-26 19:14:06
【问题描述】:

我不明白在这个取自 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)
            }
}

我了解代码的作用;我只是不明白语法。那里应该有一些等号。

【问题讨论】:

    标签: syntax kotlin synchronization singleton android-volley


    【解决方案1】:

    其实……

    那里应该有一些等号而不是冒号。

    你完全正确!例子错了!它转换为以下 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 }
                }
        }
    }
    

    【讨论】:

    • 非常感谢您解决这个问题!我开始怀疑自己的理智了。
    猜你喜欢
    • 2018-07-06
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    相关资源
    最近更新 更多