android - 如何修复 Required Iterable 但在 Kotlin 中找到了 List

标签 android kotlin mutablelist

你好,我正在学习使用 kotlin 构建应用程序,但我遇到了堆栈错误“Required Iterable, Found List”,我该如何解决这个问题?请在下面查看我的代码谢谢

class MainActivity : AppCompatActivity(),ProductView {

private lateinit var productAdapter: ProductAdapter
private var productList: MutableList<ProductData> = mutableListOf()
private lateinit var dataPresenter : DataPresenter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    initRecycler();
    getProduct()
}

private fun getProduct() {
    dataPresenter = DataPresenter(applicationContext,this)
    dataPresenter.getProduct()
}

private fun initRecycler() {
    productAdapter = ProductAdapter(this,productList)
    rvMain.layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
    rvMain.adapter = productAdapter
}

override fun showLoading() {
    pgMain.visibility = View.VISIBLE
}

override fun hideLoading() {
    pgMain.visibility = View.GONE
}

override fun showProduct(products: List<ProductData>?) {
    if (products?.size != 0){
        this.productList.clear()
        this.productList.addAll(products)  // <= Required Iterable<ProductData>, Found List<ProductData>
        productAdapter.notifyDataSetChanged()
    }
}

最佳答案

我怀疑错误信息实际上是:

Required Iterable<ProductData>, Found List<ProductData>?

最后的问号不仅仅是标点符号。这就是 Kotlin 中的可空指示符。 List<ProductData>不能是 null ,而是一个 List<ProductData>?能。我相信 addAll()需要非 null值(value)。

理想情况下,您应该更改 ProductView这样 showProduct() 的签名是fun showProduct(products: List<ProductData>) .

或者,您可以重写 showProduct()成为:

override fun showProduct(products: List<ProductData>?) {
    if (products?.size != 0){
        this.productList.clear()
        products?.let { this.productList.addAll(it) }
        productAdapter.notifyDataSetChanged()
    }
}

关于android - 如何修复 Required Iterable 但在 Kotlin 中找到了 List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55820683/

相关文章:

android - Unresolved reference : DrawImage

object - Kotlin .add覆盖MutableList中的所有列表项

android - 在kotlin中对包含数字的字符串进行排序

android - 无法在 Debian 9 上为 android 编译 Chromium - 无法创建文件。文件名太长

android - 将 2 个 SELECT 表达式与 LIMIT 组合在一起

Android - 自定义 Spinner 小部件的外观和感觉

java - 有没有办法重用一个可观察值,直到第二个可观察值在 zip 中得到 onComplete() ?

c# - Xamarin:跨平台获取设备信号强度和/或电池生命周期

inheritance - Kotlin 中的 type::class 与 type 之间有什么不同

kotlin - 在 kotlin 中可变的列表类型可以在 java 中使用吗?