androidandroid-layoutkotlintype-inference

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

  • 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:

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