0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks i change code like this ``` private val sp = //.. private fun userSP(){ //... } ```
@user9214779 That won't work in comments, use single backticks only :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.