英文:
saw this in a video referenced as an alternative to anonymous inner class, what is it?
问题
private val playbackEventListener = object : YouTubePlayer.PlaybackEventListener {
override fun onPlaying() {
Toast.makeText(this@YoutubeActivity, "onPlaying called", Toast.LENGTH_SHORT).show()
}
override fun onPaused() {
Toast.makeText(this@YoutubeActivity, "onPaused called", Toast.LENGTH_SHORT).show()
}
override fun onStopped() {
Toast.makeText(this@YoutubeActivity, "onStopped called", Toast.LENGTH_SHORT).show()
}
override fun onBuffering(p0: Boolean) {
}
override fun onSeekTo(p0: Int) {
}
}
如果这不是匿名内部类,那么第1行的声明叫做什么,它是否是一个合适的替代?另外关于 this@YouTubeActivity
,为什么不能使用 "this"?
英文:
private val playbackEventListener = object : YouTubePlayer.PlaybackEventListener {
override fun onPlaying() {
Toast.makeText(this@YoutubeActivity, "onPlaying called", Toast.LENGTH_SHORT).show()
}
override fun onPaused() {
Toast.makeText(this@YoutubeActivity, "onPaused called", Toast.LENGTH_SHORT).show()
}
override fun onStopped() {
Toast.makeText(this@YoutubeActivity, "onStopped called", Toast.LENGTH_SHORT).show()
}
override fun onBuffering(p0: Boolean) {
}
override fun onSeekTo(p0: Int) {
}
}
If this is not an anonymous inner class then what is the declaration on line 1 called and is it an appropriate alternative? Also what is up with
this@YouTubeActivity
why can't "this" be used
答案1
得分: 1
那是一个匿名类,这是Kotlin处理它们的方式
通过使用对象表达式,您现在可以定义一个匿名的、无名称的类,并同时创建一个该类的实例,称为匿名对象:
this@YouTubeActivity
这个东西是因为您在匿名类/对象的范围内,所以 this
引用的是该对象。因为您想要引用外部范围中的活动,即外部范围中的 this
,您必须指定您要引用哪个 this
。
在存在嵌套函数、lambda、接收者的情况下,这种情况经常出现,this
被重新定义(或遮蔽),您可能还需要引用外部封闭对象的引用。因此,this@WhateverThing
使您能够在不必提前创建 val myActivity = this
或其他类似变量的情况下轻松引用它们。
英文:
That is an anonymous class, it's just the way Kotlin does them
> By using an object expression, you can now define an anonymous, unnamed class and at the same time create one instance of it, called an anonymous object:
The this@YouTubeActivity
thing is because you're inside the scope of that anonymous class/object, so this
refers to the object. Since you want to refer to the activity, which is this
in an outer scope, you have to specify which this
you're talking about.
It comes up a lot where you have nested functions and lambdas, and receivers, and this
gets redefined (or shadowed), and you might need the reference to an outer, enclosing object as well. So this@WhateverThing
gives you the ability to reference them easily without having to create a val myActivity = this
or whatever in advance
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论