如何使用自定义类对象正确实现lateinit,以便在android中的onCreate()中使用,以避免'属性getter或setter expect'错误

时间:2017-11-17 10:09:49

标签: android kotlin oncreate kotlin-null-safety kotlin-lateinit

我正在尝试使用Kotlin实现Dialogflow(以前的api.ai)代理与我的Android应用程序的集成。我检查了关于kotlin lateinit的其他Q& A,并且Android中的onCreate()生命周期非常适合后期初始化实现,以避免使用空对象和相应的!!?编写脏代码访问Kotlin。但是我遇到了属性getter或setter期待的错误'在尝试lateinint自定义类的实例时。这是代码:

class AIApplication : Application() {

    private var activitiesCount: Int = 0

    var lateinit settingsManager: SettingsManager
        //private set

    private val isInForeground: Boolean
        get() = activitiesCount > 0

    override fun onCreate() {
        super.onCreate()

        settingsManager = SettingsManager(this)
    }

这给了我错误的' 预期属性getter或setter '在lateinit settingsManager行。以下是SettingsManager定义:

class SettingsManager(private val context: Context) {
    private val prefs: SharedPreferences

    private var useBluetooth: Boolean = false

    var isUseBluetooth: Boolean
        get() = useBluetooth
        set(useBluetooth) {
            this.useBluetooth = useBluetooth

            prefs.edit().putBoolean(PREF_USE_BLUETOOTH, useBluetooth).commit()
            val controller = (context.applicationContext as AIApplication).getBluetoothController()
            if (useBluetooth) {
                controller!!.start()
            } else {
                controller!!.stop()
            }
        }

    init {
        prefs = context.getSharedPreferences(SETTINGS_PREFS_NAME, Context.MODE_PRIVATE)

        useBluetooth = prefs.getBoolean(PREF_USE_BLUETOOTH, true)
    }

    companion object {

        private val SETTINGS_PREFS_NAME = "ai.api.APP_SETTINGS"
        private val PREF_USE_BLUETOOTH = "USE_BLUETOOTH"
    }

}

那么这样做的正确方法是什么?我是否需要对SettingsManager类进行一些更改?请清楚解释整个概念。

1 个答案:

答案 0 :(得分:1)

SettingsManager的lateinit声明是错误的。试试这个:

lateinit var settingsManager: SettingsManager

而不是

var lateinit settingsManager: SettingsManager

希望这有帮助。