kotlin 字段未设置值

用户9214779

这是我的 android kotlin 代码。 kotlin 版本是 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)!!

使用“sp”获取空值。使用“getSP()”获取对象


这是反编译的代码

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;
   }
}

为什么使用“sp”得到空值?kotlin 是 bug 吗?

阿列克谢·罗曼诺夫

没有错误。所有init块和属性初始值设定项都按照给定的顺序运行,然后放在sp最后,正如您在反编译代码中看到的那样。

作为旁注,在 Android 开发中,制作ContextSharedPreferences静态(在 Kotlin 的情况下,将它们放入object)是一个坏主意。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章