[英]what does the ::MainViewModel mean when pass to the singleArgViewModelFactory
in kotlin coroutines lab smaple, https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#6 在kotlin协程实验室smaple中, https: //codelabs.developers.google.com/codelabs/kotlin-coroutines/#6
it creates the viewModel by passing the MainViewModel.FACTORY(repository)
它通过传递MainViewModel.FACTORY(repository)
创建viewModel
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 MainViewModel如下,不了解::MainViewModel
在
val FACTORY = singleArgViewModelFactory(::MainViewModel)
the singleArgViewModelFactory
has constructor: singleArgViewModelFactory
具有构造函数:
singleArgViewModelFactory(constructor: (A) -> T)
which taking a function (A) -> T
, what does the ::MainViewModel
in the singleArgViewModelFactory(::MainViewModel)
mean? 它利用函数(A) -> T
,什么是::MainViewModel
在singleArgViewModelFactory(::MainViewModel)
是什么意思?
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 . ::MainViewModel
是一个函数引用 。 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). 对于类型(A) -> T
的参数,它基本上是对一个函数(在这种情况下为构造函数)的引用,该函数接受A
类型的参数并传递T
(在这种情况下为MainViewModel
本身)。
Comparing reference with its actual counterpart: 将参考文献与实际参考文献进行比较:
val ref : (A) -> T = ::MainViewModel
val ref : (A) -> T = { MainViewModel(it) } // or: = { anA : A -> MainViewModel(anA) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.