如何实例化在Kotlin中实现接口的匿名类

Ely*_*lye 13 interface kotlin

在Java中,实例化一个接口对象就像new Interface()... 一样简单,并覆盖所有必需的函数,如下所示AnimationListener

private void doingSomething(Context context) {
    Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
    animation.setAnimationListener(new Animation.AnimationListener() {
        // All the other override functions
    });
}
Run Code Online (Sandbox Code Playgroud)

但是,在Kotlin我们打字的时候

private fun doingSomething(context: Context) {
    val animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in)
    animation.setAnimationListener(Animation.AnimationListener(){
        // All the other override functions
    })
}
Run Code Online (Sandbox Code Playgroud)

它错误投诉未解决参考AnimationListener.

JB *_*zet 35

文档所述:

animation.setAnimationListener(object : Animation.AnimationListener {
    // All the other override functions
})
Run Code Online (Sandbox Code Playgroud)

  • 文档已得到改进:https://kotlinlang.org/docs/reference/nested-classes.html#anonymous-inner-classes和https://kotlinlang.org/docs/reference/classes.html#creating-instances-的类 (2认同)

Ely*_*lye 6

显然,最新的方式(使用Kotlin 1.0.5)现在没有括号,因为接口没有空的构造函数.

animation.setAnimationListener(object : Animation.AnimationListener {
    // All the other override functions
})
Run Code Online (Sandbox Code Playgroud)