Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Java interface anonymously in scala?

Tags:

java

scala

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 ?


 }

}
like image 316
rjc Avatar asked Jul 06 '11 18:07

rjc


People also ask

Can an anonymous class implement an interface in Java?

The syntax of anonymous classes does not allow us to make them implement multiple interfaces.

Can an anonymous class be declared as implementing an interface and extending a class?

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.

What are anonymous class and their types in Java with program?

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.


1 Answers

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

like image 103
Kevin Wright Avatar answered Sep 24 '22 09:09

Kevin Wright