访问封闭类的属性
我如何访问封闭类的属性? 我正在与Kotlin单身人士合作。
private object IndeterminateAnimationListener : Animation.AnimationListener { override fun onAnimationStart(animation: Animation?) {} override fun onAnimationEnd(animation: Animation?) { // How do I access the properties of the enclosing // from here? } override fun onAnimationRepeat(animation: Animation?) {} }
PS:我可以使用inner
类,我如何做同样的单身人士?
单例不能是内部的,因为它只有一个实例,内部类的实例保持对外部(封闭)类的实例的引用。 因此,单例对象不能持有对封装类的引用,并且不能访问它们的属性。
作为解决方法,请使用不是单例的匿名对象:
class A(val foo: Int) { val listener = object : AnimationListenerAdapter { override fun onAnimationEnd(animation: Animation?) { println(foo) // access to outer } } }
- 定时器崩溃KotlinNullPointerException内部片段
- BottomNavigationView链接到ViewPager,当我设置监听器bottomNavigationView,我必须点击两次执行我所做的