How to fix generic extension method signature in kotlin to resolve "Type inference error" in kotlin

I created an extension method:

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


The main use of this method:

class A {
    lateinit var text: TextView

    fun init(view:View) {
        text = view[]


This works fine, but when I try to use it without a variable:

fun test() {
    view[].visibility = View.GONE // 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 analog code in java, the methods of the View class are available without directly specifying the View type.

Is this possible in Kotlin? Perhaps some changes in generic signature in some way?


source to share

All Articles