in kotlin coroutines lab smaple, https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#6
it creates the viewModel by passing the MainViewModel.FACTORY(repository)
val viewModel = ViewModelProviders
.of(this, MainViewModel.FACTORY(repository))
.get(MainViewModel::class.java)
the MainViewModel is as below, not understand what syntax is the ::MainViewModel
used in the
val FACTORY = singleArgViewModelFactory(::MainViewModel)
the singleArgViewModelFactory
has constructor:
singleArgViewModelFactory(constructor: (A) -> T)
which taking a function (A) -> T
, what does the ::MainViewModel
in the singleArgViewModelFactory(::MainViewModel)
mean?
class MainViewModel(private val repository: TitleRepository) : ViewModel() {
companion object {
/**
* Factory for creating [MainViewModel]
*
* @param arg the repository to pass to [MainViewModel]
*/
val FACTORY = singleArgViewModelFactory(::MainViewModel)
}
......
}
fun <T : ViewModel, A> singleArgViewModelFactory(constructor: (A) -> T):
(A) -> ViewModelProvider.NewInstanceFactory {
return { arg: A ->
object : ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <V : ViewModel> create(modelClass: Class<V>): V {
return constructor(arg) as V
}
}
}
}
::MainViewModel
is a function reference. For a parameter of type (A) -> T
it basically is a reference to a function (constructor in this case) that accepts a parameter of type A
and delivers T
(which in this case is the MainViewModel
itself).
Comparing reference with its actual counterpart:
val ref : (A) -> T = ::MainViewModel
val ref : (A) -> T = { MainViewModel(it) } // or: = { anA : A -> MainViewModel(anA) }