class PlaylistViewNewModel (var playlist: Playlist?) : ViewModel() {
var limit = 100
private val name by lazy {
//lazy 只会执行一次
playlist?.id
}
//重写get方法 每次使用都是调用get(方法)
private val playlistId: String
get() = playlist?.id ?: ""
}
使用
初始化
mPlaylistVM = PlaylistViewNewModel(null)
设置变量
PlaylistVM?.playlist = playlist
ViewModel 初始化
fragment
private val mMyPlaylistVM by lazy {
ViewModelProvider(this)[MyPlaylistViewModel::class.java]
}
父fragment内共用
private val mMyPlaylistVM1 by lazy {
ViewModelProvider(requireParentFragment())[MyPlaylistViewModel::class.java]
}
activity内共用
private val mPlayVM by lazy {
ViewModelProvider(requireActivity())[PlayViewModel::class.java]
}
文章来源地址https://www.toymoban.com/news/detail-591714.html
文章来源:https://www.toymoban.com/news/detail-591714.html
到了这里,关于kotlin 初始化变量的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!