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

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
    }
}

Solution 1:

Try something like:

val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)

You can use Kotlin Android Extensions too for that. Check the doc here.
With it, you can call recycler_view directly in your code.

Kotlin Android Extensions:

  • In your app gradle.build add apply plugin: 'kotlin-android-extensions'
  • In your class add import for import kotlinx.android.synthetic.main.<layout>.* where <layout> is the filename of your layout.
  • That's it, you can call recycler_view directly in your code.

How does it work? The first time that you call recycler_view, a call to findViewById is done and cached.

Solution 2:

You're on API level 26, where the return type of findViewById is now a generic T instead of View and can therefore be inferred. You can see the relevant changelog here.

So you should be able to do this:

val recycler_view = findViewById<RecyclerView>(R.id.recycler_view)

Or this:

val recycler_view: RecyclerView = findViewById(R.id.recycler_view)