Infer generic type of a base class based on a provided superconstructor parameter type


#1

Hi, I’m wondering if it’s possible to omit the MainViewModel type in a code below:

class MainActivity : BaseBoundVmActivity<ActivityMainBinding, MainActivityViewModel>(R.layout.activity_main, MainActivityViewModel::class)

BaseBoundVmActivity.kt:

abstract class BaseBoundVmActivity<out T : ViewDataBinding, out V : ViewModel>(
        layoutId: Int,
        private val vmClass: KClass<V>
) : BaseBoundActivity<T>(layoutId) {
    protected val vm: V by lazy { ViewModelProviders.of(this).get(vmClass.java) }
}

To me it looks unnecessary to provide a second type parameter for a base class when it can be inferred from a parameter in it’s constructor. Is there a way to avoid such duplication?


#2

Well, short answer is no, it isn’t possible.

Main reason here, that for now compiler force users declare type arguments for parent class explicitly.

But if we even allow skip such parameters if they can be inferred from explicit value argument then it also cannot help you in this case, because here compiler can infer only V type argument.
May be we support special syntax for such cases like BaseBoundVmActivity<ActivityMainBinding, _>(...) but not now.