Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement only one method from interface in anonymous class [duplicate]

Tags:

java

kotlin

Is it possible in Kotlin to create an anonymous class implementing a certain interface and only implement the functions you'll need? For example I want to create a class implementing AnimationListener which has 3 methods:

  • onAnimationStart
  • onAnimationEnd
  • onAnimationRepeat

If I only want to use the onAnimationEnd callback, can I just do something like this?

object : AnimationListener {
    override fun onAnimationEnd() {
        //my implementation
    }
}

The way I've done this in Java was by creating a class which implemented the interface, just create anonymous class of that class and override the methods I need. I was hoping Kotlin has a better, less verbose, approach on this.

like image 215
dumazy Avatar asked Apr 04 '17 07:04

dumazy


People also ask

Can an anonymous type implement an interface?

No, anonymous types cannot implement an interface. From the C# programming guide: Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.

What is @anonymous class in Java?

Anonymous class usually extends a subclass or implement an interface Functional Interface is simply an interface that has exactly one abstract method. For example, the interface Animal is a Functional Interface. You can annotate functional interfaces with @FunctionalInterface

When to use anonymous inner classes in method arguments?

Anonymous inner classes in method/constructor arguments are often used in graphical user interface (GUI) applications. To get you familiar with syntax lets have a look at the following program that creates a thread using this type of Anonymous Inner class However, constructors can not be declared in an anonymous class.

Can an anonymous inner class extend a class in Java?

But anonymous Inner class can extend a class or can implement an interface but not both at a time.


1 Answers

I don't expect there's anything in Kotlin different to Java in this respect. You can, however, create your own interfaces that have default no-op implementation of methods you don't need :

interface AnimationEndListener : AnimationListener {
  fun onAnimationStart() {}
  fun onAnimationRepeat() {}
}

Then actual concrete implementation will extend AnimationEndListener and override only what's needed.

like image 165
M. Prokhorov Avatar answered Oct 07 '22 23:10

M. Prokhorov