0
votes

I have some Volley class and when I initialize it from MainActivity I pass context and expectedHosname values to it:

VolleySingleton.getInstance(context, expectedHosname).addToRequestQueue(request)

After app start expectedHostname can be changed due to user preferences, but expectedHostname is always outdated inside class VolleySingleton and has startup value. It looks like its compiled with first value and doesn't change when I pass new one through VolleySingleton.getInstance(..., ...).

As I know properties in Kotlin can be declared with var keyword and this variable has implicit getter and setter. So I can't understand why expectedHosname works like a constant. May be I have to change my companion object..?

Fragment of class

class VolleySingleton constructor(context: Context, private var expectedHostname: String) {
    companion object {
        @Volatile
        private var INSTANCE: VolleySingleton? = null
        fun getInstance(context: Context, expectedHostname: String) =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: VolleySingleton(context, expectedHostname).also {
                    INSTANCE = it
                }
            }
    }

    private fun sslSocketFactory(context: Context, expectedHost: String): SSLSocketFactory {
         // magic with expectedHost var
    }

    //OR
    private val foo: String = expectedHost.toUpperCase()
}
1

1 Answers

1
votes

Yes, expectedHostname has a setter. But you don't set it anywhere; if INSTANCE is already non-null when you call getInstance, you just return it. Something like

fun getInstance(context: Context, expectedHostname: String) =
    (INSTANCE ?: synchronized(this) {
        INSTANCE ?: VolleySingleton(context, expectedHostname).also {
            INSTANCE = it
        }
    }).also { it.expectedHostname = expectedHostname }

will work.