【问题标题】:How to initialize lateinit variable in kotlin?如何在 kotlin 中初始化 lateinit 变量?
【发布时间】:2020-04-26 20:42:18
【问题描述】:

我想在这个 Activity 中从数据类 cartDocs 中获取“id”。 我正在尝试运行此代码,但出现如下错误: kotlin.UninitializedPropertyAccessException:lateinit 属性购物车尚未初始化 我也尝试删除“?”在数据类中。但仍然是同样的问题。 我怎么解决这个问题?

class CartViewActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener {




    lateinit var cart: cartDocs

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_cart_view)

        val token = SharedPreference.getTokenInfo(this)

        Client.retrofitService.getCart(token).enqueue(object :Callback<CartResponse> {
            override fun onResponse(call: Call<CartResponse>, response: Response<CartResponse>) {
                swipeRefreshLo.setOnRefreshListener(this@CartViewActivity)
                showdata(response.body()?.docs!!)
                val itemId = cart.id
                if (itemId!=null){
                    SharedPreference.setCartId(applicationContext,itemId)
                }
            }

            override fun onFailure(call: Call<CartResponse>, t: Throwable) {

            }


        })

数据类 cartDocs

data class cartDocs(

    var id:String?=null,

    var title:String?=null,

    var stock:Int?=null,

    var availableAfter:String?=null,

    var price:Int?=null,

    var point:Int?=null,

    var mainImage:String?=null,

    var description:MutableList<cartDescription>,

    var amount:Int?=null,

    var added:String?=null,

    var options:MutableList<cartOptions>,

    var unitPrice:Int?=null,

    var unitPoint:Int?=null,

    var totalPrice:Int?=null,

    var totalPoint:Int?=null
)



【问题讨论】:

  • 未初始化的是cart
  • Nullable 类型 (?) 不会产生此错误。
  • 那么如何初始化购物车??
  • 通过分配给它。 cart = cartDocs().
  • @RequiresApi(Build.VERSION_CODES.N) 应该已经引起了怀疑......

标签: android-studio kotlin retrofit


【解决方案1】:

lateinit 设计用于在对象创建后的某个时间需要初始化变量的情况 - 例如像 dagger 这样的框架。事实上,它允许像普通的not null 值一样使用lateinit 变量(并去掉不必要的?/!! 运算符),但程序员有责任确保在使用之前初始化该值。

在您的情况下,您尝试在初始化之前使用该变量。所以,你得到了例外。您需要在某个时候初始化该值。但是,我会考虑设计 - 似乎您需要的是 nullable 类型并且在这里使用 lateinit 是不合理的。它会强制您在使用该值之前检查该值是否不为空。

如果您对 JVM 中的 lateinit 设计感兴趣,可以查看我对其他问题的旧答案:How to uninitialize lateinit in Kotlin

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2022-12-15
    • 1970-01-01
    • 2020-08-08
    • 2021-12-11
    相关资源
    最近更新 更多