Android 在Kotlin中初始化SharedReference的正确方法

Android 在Kotlin中初始化SharedReference的正确方法,android,kotlin,sharedpreferences,Android,Kotlin,Sharedpreferences,我对科特林很陌生。以前,我曾在活动中声明SharedReference,如下所示: class MainActivity extends AppCompatActivity { SharedPreferences main; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); main = ge

我对科特林很陌生。以前,我曾在活动中声明SharedReference,如下所示:

class MainActivity extends AppCompatActivity {
    SharedPreferences main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        main = getSharedPreferences("main", MODE_PRIVATE);
    }
}
这允许我在整个类中使用主实例。我想实现类似的功能。我目前使用的lateinit变量如下:

但我不确定这样做是否正确。 此外,这是一个var。据我所知,通常建议在实例不会发生更改的情况下使用val。在这种情况下,初始化后main不会发生更改。那么这种方法正确吗?

使用lateinit非常好。毕竟,它是为了这个目的而存在的

不过,您可以使用一个稍微干净一点的解决方案:lazy init:

val main by lazy { getSharedPreferences("main", Context.MODE_PRIVATE) }
这仅在第一次引用main时调用getSharedReferences,然后存储该实例。这类似于Java中的操作方式,但不需要拆分行。

使用lateinit非常好。毕竟,它是为了这个目的而存在的

不过,您可以使用一个稍微干净一点的解决方案:lazy init:

val main by lazy { getSharedPreferences("main", Context.MODE_PRIVATE) }
这仅在第一次引用main时调用getSharedReferences,然后存储该实例。这类似于Java中的操作方式,但不需要拆分行。

事实上,val更好。您可以通过延迟初始化获得一个:

class MainActivityKotlin : AppCompatActivity() {
    private val sharedPrefs by lazy { getSharedPreferences("main", Context.MODE_PRIVATE) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /* initialisation is removed from here, as it is now lazy */
    }

    fun otherFunction() {
        // the first use of the shared preference will trigger its initialisation
        val prefInt = sharedPrefs.getInt("key", 0)
    }
}
事实上,val更好。您可以通过延迟初始化获得一个:

class MainActivityKotlin : AppCompatActivity() {
    private val sharedPrefs by lazy { getSharedPreferences("main", Context.MODE_PRIVATE) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /* initialisation is removed from here, as it is now lazy */
    }

    fun otherFunction() {
        // the first use of the shared preference will trigger its initialisation
        val prefInt = sharedPrefs.getInt("key", 0)
    }
}

看起来很完美。我也可以用val而不是var来使用这种方法。看起来很完美。使用这种方法,我也可以使用val而不是var。