实现Java接口的Scala类-具有相同擦除的双重定义

xxls0lw8  于 2023-04-21  发布在  Scala
关注(0)|答案(1)|浏览(81)

我有一个Java接口:

public interface FooJava {
    void consume(String... strings);
    void consume(Integer... ints);
}

我想在Scala中实现它:

class BarScala extends FooJava {
  override def consume(strings: String*): Unit = ???
  override def consume(ints: Integer*): Unit = ???
}

不幸的是,这失败了:

double definition:
override def consume(strings: String*): Unit at line 4 and
override def consume(ints: Integer*): Unit at line 5
have same type after erasure: (strings: Seq)Unit
  override def consume(ints: Integer*): Unit = ???

我知道Java编译器创建Bridge方法,而Scala编译器不这样做。
我尝试了一种使用DummyImplicates的方法:Are DummyImplicits used, and if so, how?,但它显然失败了-consume(ints: Integer*)(implicit i: DummyImplicit)没有覆盖任何内容

class BarScala extends FooJava {
  override def consume(strings: String*): Unit = ???
  override def consume(ints: Integer*)(implicit i: DummyImplicit): Unit = ???
}

我没有Java接口。有可能在Scala中实现它吗?我使用Scala 2.12

v8wbuo2f

v8wbuo2f1#

你可以在Java中用中间抽象类实现接口,在Scala中扩展这个抽象类

abstract class FooJavaImpl implements FooJava {
    public abstract void consumeInts(Integer... ints);

    @Override
    public void consume(Integer... ints) {
        consumeInts(ints);
    }
}
class BarScala extends FooJavaImpl {
  override def consume(strings: String*): Unit = ???
  def consume(ints: Integer*)(implicit i: DummyImplicit): Unit = ???
  override def consumeInts(ints: Integer*): Unit = consume(ints: _*)
}

或者不带DummyImplicit

abstract class FooJavaImpl implements FooJava {
    public abstract void consumeInts(Integer... ints);

    public abstract void consumeStrs(String... strs);

    @Override
    public void consume(Integer... ints) {
        consumeInts(ints);
    }

    @Override
    public void consume(String... strs) {
        consumeStrs(strs);
    }
}
class BarScala extends FooJavaImpl {
  override def consumeInts(ints: Integer*): Unit = ???
  override def consumeStrs(strs: String*): Unit = ???
}

相关问题