Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override and implement fn from class in interface

I want to override toString() in an interface and have objects that implement that interface to default to using that method (eg: not shadowed)

interface SingletonObjectTrait {
  fun toString(): String = this.javaClass.simpleName
}

Is there a straightforward way to define such an interface, preferably with minimal configuration at implementation

object MyEvent: SomeEventLogic(), SomeEventType, SingletonObjectTrait
class SomeEventLogic {}
interface SomeEventType {}
like image 812
xst Avatar asked Mar 04 '23 21:03

xst


1 Answers

That's not possible, I'm afraid.

Method implementations in interfaces work much like default methods in Java: they're used only if the implementing class doesn't have an implementation already.  But every class already inherits toString() from Any, so the default would never be used.

In fact, the compiler has a specific error for this — if you try to implement toString() in an interface, it says:

An interface may not implement a method of 'Any'

I can't see a good way around this.

As Erik says, one option is to change the interface to an abstract class; but of course that's not viable if any implementations already extend another class.

Another option might be to implement a different method in the interface, and in the comments instruct implementing classes to override toString() and call that method.  Not automatic, but less work for implementers, and less repetition.

like image 80
gidds Avatar answered Mar 16 '23 14:03

gidds