避免在Kotlin中出现竞争状况,Smartcast是不可能的运行时异常

时间:2018-08-20 15:59:10

标签: android android-recyclerview kotlin recycler-adapter

该行:

  

viewAdapter.setTitleData(bezinningModels)

以下代码段中的

给了我运行时警告:

  

无法智能地投射到“ BezinningAdapter”,因为“ viewAdapter”   是一个可变属性,本来可以更改

我浏览了很多带有类似运行时警告的帖子,并且我理解了为什么会发生这种情况。基本上Kotlin希望避免出现竞争情况,以使可变对象的值不会发生变化,但是我仍然无法避免该错误,因此我可以将改造调用调用到RecyclerView Array中 我试图将var的值从val更改为RecyclerView,但没有用

以下是导致问题的代码段:

@RequiresApi(Build.VERSION_CODES.HONEYCOMB)
class MainFragment : android.app.Fragment() {




private lateinit var viewManager: RecyclerView.LayoutManager
private lateinit var recyclerView: RecyclerView

private lateinit var viewAdapter: RecyclerView.Adapter<*>

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    val view = inflater!!.inflate(R.layout.bezinning_fragment, container, false)

   viewManager=LinearLayoutManager(activity)
    viewAdapter=BezinningAdapter()

    recyclerView = view.findViewById(R.id.recycler_view) as RecyclerView
    recyclerView.setHasFixedSize(true)
    recyclerView.layoutManager=viewManager
    recyclerView.adapter=viewAdapter


    val subscribe = bezinningListViewModel!!.showBezinningLijst("132")
            ?.subscribeOn(schedulerProvider!!.io())
            ?.observeOn(schedulerProvider!!.ui())
            ?.subscribe(object : FlowableSubscriber<List<BezinningModel>> {
                override fun onError(t: Throwable?) {
                    Log.d("IVO", "onError: ")
                }

                override fun onComplete() {
                    Log.d("IVO", "onComplete: ")
                }

                override fun onSubscribe(s: Subscription) {
                    s.request(Long.MAX_VALUE);

                }

                override fun onNext(bezinningModels: List<BezinningModel>?) 
   {

                    val JSONResponseBody = bezinningModels!! 
[0].attribute.body
                    viewAdapter.setTitleData(bezinningModels)


                    val bodyBezinningParsedHtml = 
Html.fromHtml(JSONResponseBody)



                }


            })

    return view

}



}

1 个答案:

答案 0 :(得分:1)

如果您知道viewAdapter将是BezinningAdapter,请这样声明:

private lateinit var viewAdapter: BezinningAdapter<*>