gpt4 book ai didi

android - obj.apply{ func1() } 的结果与 obj.func1() 不同

转载 作者:行者123 更新时间:2023-12-05 00:18:59 25 4
gpt4 key购买 nike

在 Kotlin 中,apply{}定义为 inline fun <T> T.apply(block: T.() -> Unit): T我以为使用这个功能是为了最小化这段代码

obj.func1()
obj.func2()
obj.func3()
...
obj.apply {
func1()
func2()
func3()
}
但现在我认为它有一些完全不同的实际用例。在我的 android studio 项目中,我得到了这个日志
2020-12-08 13:3:22.648 28006-28006/com.skb.skara D/VideoViewActivity: onStart: pos 2677
2020-12-08 13:3:22.649 28006-28006/com.skb.skara D/VideoViewActivity: initializePlayer: seeked to 0
2020-12-08 13:3:22.650 28006-28006/com.skb.skara D/VideoViewActivity: onStart: pos 2677
对于此代码
private var currentPosition: Int

override fun onStart() {
super.onStart()
Log.d(TAG, "onStart: pos $currentPosition")
initializePlayer()
Log.d(TAG, "onStart: pos $currentPosition")
if (currentPosition == 0) {
Log.d(TAG, "onStart: vid start")
fullscreen_video.start()
}
show()
}

private fun initializePlayer() {
fullscreen_video.apply {
setVideoPath(videoUrl)
seekTo(currentPosition)
Log.d(TAG, "initializePlayer: seeked to $currentPosition")
}
}
然后我改了 initialisePlayer作用于此
private fun initializePlayer() {
fullscreen_video.setVideoPath(videoUrl)
fullscreen_video.seekTo(currentPosition)
Log.d(TAG, "initializePlayer: seeked to $currentPosition")
}
然后我得到了这个日志
2020-12-08 13:12:53.548 28006-28006/com.skb.skara D/VideoViewActivity: onStart: 2677
2020-12-08 13:12:53.550 28006-28006/com.skb.skara D/VideoViewActivity: initializePlayer: seeked to 2677
2020-12-08 13:12:53.550 28006-28006/com.skb.skara D/VideoViewActivity: onStart: 2677
有人请解释这种行为并解释范围函数的使用 apply{}

最佳答案

小心,VideoView有自己的currentPosition .访问 currentPosition在其apply block 将获得 VideoView 的 currentPosition .

private fun initializePlayer() {
fullscreen_video.apply {
setVideoPath(videoUrl)
seekTo(currentPosition) // This will use VideoView.currentPosition
Log.d(TAG, "initializePlayer: seeked to $currentPosition") // This, too
}
}
解释一下 apply :

The context object is available as a receiver (this). And this always can be omitted.


如果您想访问 currentPosition您在上面声明,请使用 this@YourActivity.currentPosition .替换 YourActivity与您的 Activity 。

关于android - obj.apply{ func1() } 的结果与 obj.func1() 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65195156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com