Not able to "findViewById" in Kotlin. Getting error "Type inference failed"

Viewed 87078

I am getting the following error when I try to find a RecycleView by id.

Error:- Type inference failed: Not enough information to infer parameter T

Error

Code:

class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}
9 Answers

Was unable to access the ui components like OP faced looks like below was needed inside app gradle:

plugins {
    ...
    id 'kotlin-android-extensions'
}

Even though after adding this line android studio was still not able to auto resolve the imports for kotlin synthetics so you may need to invalidate cache and restart.

If still not working then import manually depending on views

  • activity /fragment view: import kotlinx.android.synthetic.main.<your_activity_view>.*
  • normal views : import kotlinx.android.synthetic.main.<your_layout_view>.view.*

Update - 2

If you are getting this info warning -

Warning: The 'kotlin-android-extensions' Gradle plugin is deprecated.

plugin 'kotlin-android-extensions' is going to be deprecated. So add below in your app gradle

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

You don't even have to create an object to do things with a view. You can just use the id. For example, Kotlin

recycle_view.adapter = adapter

is same as, Java

RecycleView recycle_view = (RecycleView) findViewById(recycle_view);
recycle_view.setAdapter(adapter);
Related