• Latest Code...

    Solution: “Type inference failed” error by using "findViewById” in Kotlin

    If you get any error when you are using kotlin and references views to kotlin, then most of time every developer faced  “Type inference failed” error  in Kotlin.

    We have few option for such kind of error in kotlin,

    var tvName = findViewById(R.id.txtName) as TextView
    var tvName = findViewById<TextView>(R.id.txtName) 
    You can use Kotlin Android Extensions too for that. Check the doc here.

    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. for example activity_main
    • That's it, you can call TextView directly in your code.
    Sometimes its works like this:

    var tvName:TextView = findViewById(R.id.txtName) as TextView
    If you are using Anko, then you have to do this:
    var tvName:TextView = find(R.id.txtName)
    Where bind internally work like this:
    fun <T : View> Activity.bind(@IdRes res : Int) : T {
        return findViewById(res) as T}
    More info:
    #HappyCoding #ILoveKotlin #PrAndroid


    Most recent Elastic Search tutorials for beginner, intermediate and advance level developer, Yubraj Pokharel, in CodingWorkspace