UKR
UKR

Reputation: 41

Type inference failed. Please try to specify type argument explicity : Kotlin

    class SetContentView<in R : Activity, out T : ViewDataBinding>(
     @LayoutRes private val layoutRes: Int) {
     private var value : T? = null
     operator fun getValue(thisRef: Activity, property: KProperty<*>): T {

     value = value ?: DataBindingUtil.setContentView<T>(thisRef, layoutRes)
     return value
     }
    }

    val binding: ActivityDogBinding by contentView(R.layout.activity_dog)

DogActivity.kt

    fun <R : Activity, T : ViewDataBinding> contentView(@LayoutRes layoutRes: Int):
     SetContentView<R, T> {
     return SetContentView(layoutRes)
    }

When I try to call in the activity as

val binding: ActivityLoginBinding by contentView(layoutRes = R.layout.activity_login)

Its throwing error as

Type inference failed. Please try to specify type argument explicitly : Kotlin

in Android Studio. I tried similar in IntelliJ its working fine.

Upvotes: 4

Views: 7980

Answers (1)

Lovis
Lovis

Reputation: 10057

You need to use the R type parameter for your getValue method:

operator fun getValue(thisRef: R, property: KProperty<*>): T {
  ...
}

Upvotes: 3

Related Questions