Kotlin自定义获取执行方法调用吗 [英] Does Kotlin custom get execute method call

查看:124
本文介绍了Kotlin自定义获取执行方法调用吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为提高对SharedPreferences.Editor的调用的可读性,我想使用Kotlin变量,该变量将在每次需要新的SharedPreferences.Editor时执行"getSharedPreferences.edit()".最初,我将使用类似这样的内容:

To increase the readability of calls to SharedPreferences.Editor I want to use a Kotlin variable that will execute 'getSharedPreferences.edit()' each time I need a new SharedPreferences.Editor. Initially I was going to use something like this:

val editPreferences: SharedPreferences.Editor = Application.getSharedPreferences("preferences", Context.MODE_PRIVATE).edit()

但是后来我得知,当我真正希望每次调用"editPreferences"创建新编辑器时,"editPreferences"将保留对同一编辑器的引用.

But then I was informed that 'editPreferences' will hold the reference to the same editor when what I really want it to create a new editor each time the 'editPreferences' is called.

如果使用了自定义吸气剂,每次都会返回一个新的编辑器吗?像这样:

If a custom getter was used would a new editor be returned each time? Something like this:

val editPreferences: SharedPreferences.Editor 
    get() = Application.getSharedPreferences("preferences", Context.MODE_PRIVATE).edit()

仍然使用Kotlin启动并运行,并且不确定get()方法是否保留对编辑器的引用,而不是创建一个新的引用.

Still getting up and running with Kotlin and am not sure if the get() method would hold reference to the editor instead of creating a new one.

推荐答案

第二个属性声明适合您的需求:它具有

The second property declaration suits your needs: it has a custom getter, thus getting the property value will always execute the getter, and the value is not stored (the property has no backing field).

您可能会对get() = ...中的等号感到困惑,但这只是一个

You are probably confused by equals sign in get() = ..., but it is just a single-expression shorthand for the equivalent form of getter:

val editPreferences: SharedPreferences.Editor 
    get() { 
         return Application
              .getSharedPreferences("preferences", Context.MODE_PRIVATE)
              .edit()
    }

这篇关于Kotlin自定义获取执行方法调用吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆