开发者

How to implement Java interface anonymously in scala?

开发者 https://www.devze.com 2023-03-17 14:23 出处:网络
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:

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 ?


 }

}


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


val bar = new Bar {
  def baz(st: String) {
    // method impl
  }

  def jaz() {
    // method impl
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消