开发者

How can I implement a Java interface with variadic methods in Scala?

I am implementing a Java interface containing variadic methods like so:

interface Footastic { 
  void foo(Foo... args);
}

Is it possible to implem开发者_开发问答ent this interface in Scala? Variadic functions are handled differently in Scala, so the following won't work:

class Awesome extends Footastic {
  def foo(args: Foo*): Unit = { println("WIN"); }
  // also no good: def foo(args: Array[Foo]): Unit = ...
}

Is this even possible?


The code you've written works as-is.

The scala compiler will generate a bridge method which implements the signature as seen from Java and forwards to the Scala implementation.

Here's the result of running javap -c on your class Awesome exactly as you wrote it,

public class Awesome implements Footastic,scala.ScalaObject {
  public void foo(scala.collection.Seq<Foo>);
    Code:
       0: getstatic     #11                 // Field scala/Predef$.MODULE$:Lscala/Predef$;
       3: ldc           #14                 // String WIN
       5: invokevirtual #18                 // Method scala/Predef$.println:(Ljava/lang/Object;)V
       8: return

  public void foo(Foo[]);
    Code:
       0: aload_0
       1: getstatic     #11                 // Field scala/Predef$.MODULE$:Lscala/Predef$;
       4: aload_1
       5: checkcast     #28                 // class "[Ljava/lang/Object;"
       8: invokevirtual #32                 // Method scala/Predef$.wrapRefArray:([Ljava/lang/Object;)Lscala/collection/mutable/WrappedArray;
      11: invokevirtual #36                 // Method foo:(Lscala/collection/Seq;)V
      14: return

  public Awesome();
    Code:
       0: aload_0
       1: invokespecial #43                 // Method java/lang/Object."<init>":()V
       4: return
}

The first foo method with with Seq<Foo> argument corresponds to the Scala varargs method in Awesome. The second foo method with the Foo[] argument is the bridge method supplied by the Scala compiler.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜