首页 文章

在Android Studio(Kotlin)中处理赋值运算符的歧义

提问于
浏览
1

我最近开始在kotlin开发Android应用程序并遇到了这个问题 . 我有var员工Arraylist声明并在我的活动开始时分配了null,后来我在我的OnCreate方法中添加了字符串值 .

enter image description here

var employees: ArrayList<String>?= null

现在,当我向其添加值时,我得到一个赋值运算符歧义错误 .

enter image description here

在互联网上进行一些研究后,我发现=具有可变列表的操作有两种可能的解释 - 要么将项目附加到现有列表,要么通过将新值附加到旧列表来创建新列表并存储引用到变量中的新列表 . from here

现在我的问题是如何让编译器从其中一个解释中选择添加到我的可变列表中 .

谢谢 .

2 回答

  • 0

    您可以根据自己的要求自行选择一个 .

    如果您只想将员工添加到 employees

    var employees: ArrayList<String>? = null
    employees?.plusAssign("employee")
    

    如果您希望将 employees 分配给包含添加的员工的新 List

    var employees: List<String>? = null
    employees = employees?.plus("employee")
    

    注意声明之间的区别 . 但我认为最好只使用 ArrayListadd() 函数添加一名员工:

    var employees: ArrayList<String>? = null
    employees?.add("employee")
    

    我认为毕竟没有必要坚持赋值运算符,它只是方法调用的一种方便的方法:)

  • 1

    如果您使用 val 而不是 var ,则运算符将按预期工作:

    val myArrayList = arrayListOf<String>()

    myArrayList += "firstElement" // works fine

相关问题