Simplify ViewModelProvider.Factory() Implementation with Kotlin Lambda and Object Expressions

Learn how to streamline the implementation of ViewModelProvider.Factory() using Kotlin Lambdas and Object Expressions with examples.

Vincent Tsen

--

If you are like me and still have not gotten used to the Dependency Injection framework (don’t you think it complicates things?), you probably have been implementing the ViewModelProvider.Factory() interface for your view models that has custom constructor parameters.

Multiple ViewModel Factory Classes

class AViewModelFactory(private val repository: ARepository) :
ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return AViewModel(repository) as T
}
}

For example, AViewModelFactory is the view model factory class that creates ViewModel which takes in ARepository as a constructor parameter. So what if you have another ViewModel to create? Then, you need to implement another factory class (i.e. BViewModelFactory)

class BViewModelFactory(private val repository: BRepository) :
ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return…

--

--