Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate an anonymous class that implements an interface in Kotlin

In Java, instantiate an interface object is as easy as new Interface()... and override all the required functions as below, on 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
    });
}

However, in Kotlin when we type

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

It error complaints unresolved References AnimationListener.

like image 553
Elye Avatar asked Jun 14 '16 07:06

Elye


2 Answers

As explained in the documentation:

animation.setAnimationListener(object : Animation.AnimationListener {
    // All the other override functions
})
like image 186
JB Nizet Avatar answered Nov 03 '22 08:11

JB Nizet


Apparently the latest way (using Kotlin 1.0.5) of doing it is now without the parenthesis, given there's no empty constructor for the interface.

animation.setAnimationListener(object : Animation.AnimationListener {
    // All the other override functions
})
like image 31
Elye Avatar answered Nov 03 '22 09:11

Elye