我想从本活动的数据类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
)
答案 0 :(得分:0)
lateinit
是为在对象创建后需要初始化变量的情况而设计的,例如dagger
之类的框架。实际上,它允许将lateinit
变量用作常规not null
值(并摆脱不必要的?/!!
运算符),但是程序员有责任确保在使用前初始化该值。
在您的情况下,您尝试在初始化变量之前使用该变量。因此,您将获得例外。您需要在某个时候初始化该值。但是,我会考虑设计-似乎您需要的是nullable
类型,在这里使用lateinit
是不合理的。它将强制您在任何使用该值之前检查value是否不为空。
如果您对JVM中的lateinit
设计感兴趣,则可以看到我对其他问题的旧答案:How to uninitialize lateinit in Kotlin