How can I implement Java interface with variable methods in Scala?

I am implementing a Java interface containing variative methods such as:

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 will not work:

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

Is it possible?

+6
source share
1 answer

The code you wrote works as it is.

The scala compiler will generate a bridge method that implements the signature, as seen from Java, and proceeds to implement the scala.

Here the result of running javap -c of your Awesome class is exactly the same 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 the argument Seq <Foo> corresponds to the scala varargs method in Awesome. The second foo method with the argument Foo [] is the bridge method provided by the scala compiler.

+9
source

Source: https://habr.com/ru/post/897922/


All Articles