首页 > 解决方案 > 带有对象问题的 Kotlin 单例

问题描述

我正在尝试用 Kotlin 做单例模式,但我不明白为什么我在这里得到空指针异常

object AppController : Application() {
    private val queue: RequestQueue = Volley.newRequestQueue(applicationContext)

   fun getRequestQueue(): RequestQueue {
        return queue
    }
}

在我的主要活动中,我打电话给:

private val controller  = AppController
private val queue = AppController.getRequestQueue()

感谢您的帮助。对不起。我不确定为什么代码格式不正确。

标签: androidkotlinsingleton

解决方案


只需将对象更改为类,可能android初始化它有问题

class AppController : Application() {
    private val queue: RequestQueue = Volley.newRequestQueue(applicationContext)

   fun getRequestQueue(): RequestQueue {
        return queue
    }
}

干杯


推荐阅读