Suppose I have a Java inteface
public interface Bar {
public void baz(String st)
public void jaz()
}
I want to implement above interface anonymously in scala within a function body like:
def foo() = {
val bar : Bar = new Bar() {
// how to do that ?
}
}
The syntax of anonymous classes does not allow us to make them implement multiple interfaces.
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.
In Java, a class can contain another class known as nested class. It's possible to create a nested class without giving any name. A nested class that doesn't have any name is known as an anonymous class. Anonymous classes usually extend subclasses or implement interfaces.
If I had to, I'd write it as:
val bar = new Bar {
def baz(st: String): Unit = {
// method impl
}
def jaz(): Unit = {
// method impl
}
}
Though my preference is to avoid side-effecting methods as much as possible, they don't play very nicely with functional programming
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With