6

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

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

Is it possible to implement 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?

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.