简体   繁体   English

如何在Scala中使用可变方法实现Java接口?

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

I am implementing a Java interface containing variadic methods like so: 我正在实现一个包含可变方法的Java接口,如下所示:

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

Is it possible to implement this interface in Scala? 是否可以在Scala中实现此接口? Variadic functions are handled differently in Scala, so the following won't work: 变量函数在Scala中的处理方式不同,因此以下方法不起作用:

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. scala编译器将生成一个桥接方法,该方法实现从Java看到的签名并转发到Scala实现。

Here's the result of running javap -c on your class Awesome exactly as you wrote it, 这是在你的类上运行javap -c的结果,就像你写的那样,

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. 使用Seq <Foo>参数的第一个foo方法对应于Awesome中的Scala varargs方法。 The second foo method with the Foo[] argument is the bridge method supplied by the Scala compiler. 带有Foo []参数的第二个foo方法是Scala编译器提供的桥接方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM