你好,我正在学习使用 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/