Reputation: 309
here is my kotlin code for android。kotlin version is 1.2.41
private fun getUserFromSharePreferences() {
Timber.d("getSP() = ${getSP()}") // sharedPreferences
Timber.d("sp = ${sp}") // null
}
private fun getSP() = CoreApplication.context.getSharedPreferences(FLAG_SP_USER, Context.MODE_PRIVATE)
private val sp = CoreApplication.context!!.getSharedPreferences(FLAG_SP_USER, Context.MODE_PRIVATE)!!
use "sp" get null. use "getSP()" get object
here is decompiled code
public final class UserKt {
private static User currentUser = getUserFromSharePreferences();
private static final SharedPreferences sp;
private static final void getUserFromSharePreferences() {
Timber.d("getSP() = " + getSP(), new Object[0]);
Timber.d("sp = " + sp, new Object[0]);
}
private static final SharedPreferences getSP() {
return CoreApplication.context.getSharedPreferences("FLAG_SP_USER", 0);
}
static {
Context var10000 = CoreApplication.context;
if(CoreApplication.context == null) {
Intrinsics.throwNpe();
}
SharedPreferences var0 = var10000.getSharedPreferences("FLAG_SP_USER", 0);
if(var0 == null) {
Intrinsics.throwNpe();
}
sp = var0;
}
}
why use "sp" get the null? is kotlin bug?
Upvotes: 0
Views: 220
Reputation: 170733
No bug. All init
blocks and property initializers run in the given order, and you put sp
at the end, as you can see in the decompiled code.
As a side note, making Context
and SharedPreferences
static (in case of Kotlin, putting them into an object
) is a bad idea in Android development.
Upvotes: 1