列表按值传递?

时间:2018-10-29 12:37:13

标签: android kotlin

我正在尝试复制其中包含arraylists的列表,但是当我编辑复制的值时,原始值会更改,这意味着要传递我的ref,我尝试了各种方法,例如使用复制每个项目的方法,或从原始项目创建一个列表/可变列表,但没有用,所以我的问题是如何在kotlin中传递值而不是ref?

我也将原始图像制成val及其字段。

class FAQAdapter(val faqModel: MutableList<FAQSection>) : RecyclerView.Adapter<FAQAdapter.ViewHolder>() {

    val faqOriginal: List<FAQSection>
    var faqSectionsCopy: MutableList<FAQSection>

    init {
        faqOriginal = faqModel
        faqSectionsCopy = faqModel.toMutableList()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.faq_section_item, parent, false))
    }

    override fun getItemCount(): Int {
        return faqSectionsCopy.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.faqSectionHeading.text =
                faqSectionsCopy.get(holder.adapterPosition).sectionheader

        holder.questionsRecyclerView.layoutManager =
                LinearLayoutManager(holder.itemView.context,
                        LinearLayoutManager.VERTICAL, false)

        holder.questionsRecyclerView.adapter =
                FAQQuestionsAdapter(faqSectionsCopy.get(holder.adapterPosition)
                        .faqQuestions)

        holder.questionsRecyclerView.setHasFixedSize(true)

        holder.questionsRecyclerView.minimumHeight = convertDpToPx(holder.itemView.context, 88) * faqSectionsCopy.get(holder.adapterPosition).faqQuestions.size

    }

    fun filter(text: String) {
        var text = text.trim().toLowerCase()
//        faqSectionsCopy.clear()

        if (text.isEmpty()) {
//            faqSectionsCopy = faqModel as ArrayList<FAQSection>
        } else {
            text = text.toLowerCase()

            faqSectionsCopy.map {
                faqSectionsCopy[0].faqQuestions = it.faqQuestions.filter { it.question.contains(text) } as ArrayList<FAQQuestion>
            }

        }
        notifyDataSetChanged()
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var questionsRecyclerView = itemView.faqQuestionsRecyclerView
        var faqSectionHeading = itemView.faqHeading
    }
}

2 个答案:

答案 0 :(得分:0)

您不能在 Kotlin Java 中按值传递数据。相反,您应该确保在检索数据时处理副本:

binding

然后,toMutableList扩展功能将创建列表的可变副本,因此原始副本不会更改。由于参数的两个级别均为fun withList(listOfLists: List<List<Any>>) { ... val list = listOfLists[0].toMutableList() ... } 类型,因此值本身是不可变的。

答案 1 :(得分:0)

实际上,Java / Kotlin中的每个数据传递都是按值进行的。除了这种情况下,您要传递值引用,而不是列表本身。

要传递列表的副本,您可以

  • 使用yourList.toList()传递,它将复制列表并返回不可变的列表
  • 明确创建新的可变ArrayList(yourList)