如何修复Kotlin中必需的Iterable但找到列表

Asq*_*sqa 0 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()
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Com*_*are 5

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

Required Iterable<ProductData>, Found List<ProductData>?
Run Code Online (Sandbox Code Playgroud)

最后的问号不只是标点符号。那是Kotlin中的可为空的指标。一个List<ProductData>不能是null,但是List<ProductData>?可以。而且我认为这addAll()需要非null价值。

理想情况下,你应该改变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()
    }
}
Run Code Online (Sandbox Code Playgroud)