简体   繁体   中英

How to fix signature of generic extension method in kotlin to resolve “Type inference failed” in kotlin

I have created extension method:

@Suppress("UNCHECKED_CAST")
operator fun <T : View> View.get(@IdRes id:Int): T  =
        this.findViewById(id) as T

Main usage of this method:

class A {
    lateinit var text: TextView

    fun init(view:View) {
        text = view[R.id.text]
    }
}

This works perfectly, but when I try use it without variable:

fun test() {
    view[R.id.text].visibility = View.GONE // error
}

Error:

Type inference failed: Not enough information to infer parameter T in 
operator fun <T : View> View.get(id: Int): T
Please specify it explicitly.

If I write the analog code in java, methods of class View available without direct specification of View type.

Is it possible in kotlin? Maybe do some changes in signature of generic type somehow?

It is not possible to specify the generics type on the get operator, and it is also not possible to the compiler to infer what type does that get should return.

You can call the get function as an ordinary function view.get<TextView>(R.id.text) , without using the operator overloading convention.

To achieve the desired functionality, you can use the Kotlin Android Extensions as suggested by @Miha_x64, without the need to use the findViewById method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM