刚刚开始使用Kotlin进行Android开发.我的arraylist声明如下-

var day1: ArrayList<DietPlanDetailModel>? = null

现在我试图通过元素的位置来访问它

    val dietPlan= day1[position]

但我的编译时错误率正在下降-

Only safe or non null assserted calls are allowed on a nullable receiver type of arraylist

Why am i getting this error and how can i resolve it?

推荐答案

The problem is, that you defined the ArrayList as nullable. You have two options here:

  1. don't define the variable nullable (this depends on your code):
var day1: ArrayList<DietPlanDetailModel> = ArrayList()
  1. access your data-structure with a null check:
val dietPlan= day1?.get(position)

Kotlin相关问答推荐

将基于注册的服务转换为流

Kotlin 海峡没有结束

Kotlin中一个接口的实现问题

有没有一种简单的方法来识别物体?

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

当我通过媒体通知更改音乐时不要更新我的 UI

如何使用 Kotlin Maven 更改 Minecraft 插件中的 Shulker GUI 标题

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

Kotlin 接口类型参数

Kotlin:使用另一个列表和字母顺序对列表进行排序的有效方法

错误:cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

Android 在将 androidx 生物识别更新为 1.0.0-alpha04 后崩溃

Firebase 权限被拒绝

主机名不能为空

@uncheckedVariance 在 Kotlin 中?

封闭 lambda 的隐式参数被shadowed

在 gradle android library kotlin 项目中禁用 META-INF/* 生成

Kotlin协程无法处理异常

在 Kotlin 中声明 Byte 会出现编译时错误The integer literal does not conform to the expected type Byte

函数引用和lambdas