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

时间:2016-06-14 07:40:51

标签: 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
    });
}

然而,在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
    })
}

错误投诉未解决引用AnimationListener。

2 个答案:

答案 0 :(得分:31)

the documentation中所述:

animation.setAnimationListener(object : Animation.AnimationListener {
    // All the other override functions
})

答案 1 :(得分:6)

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

animation.setAnimationListener(object : Animation.AnimationListener {
    // All the other override functions
})