简体   繁体   English

Scala-在Scala类中重写Java接口方法

[英]Scala - Overriding a Java interface method in a Scala class

I have a Java interface Writer defined as following: 我有一个Java接口Writer定义如下:

public interface Writer<K, V> {

    Iterator<Product2<K, V>> iterator ();
}

And i am trying to implement this interface in a Scala class ExternalWriter which is as following: 我正在尝试在Scala类ExternalWriter中实现此接口,如下所示:

private class ExternalWriter[K, V, C]
  extends Logging
  with Writer[K, V] {

    override def iterator(): Iterator[Product2[K, C]] = {
        partitionedIterator.flatMap(pair => pair._2)
  }
}

But when I try to compile this code, I get an error: 但是,当我尝试编译此代码时,出现错误:

Error: Overriding method iterator in trait SortShuffleFileWriter of type ()Iterator[Product2[K,V]]; 错误:类型为()Iterator [Product2 [K,V]];的特征SortShuffleFileWriter中的重写方法迭代器; method iterator has incompatible type override def iterator(): Iterator[Product2[K, C]] = { 方法迭代器具有不兼容的类型重写def iterator():Iterator [Product2 [K,C]] = {

How do I fix this? 我该如何解决?

Why did you change V to C ? 为什么将V更改为C

Your override method should be, 您的替代方法应为

override def iterator(): Iterator[Product2[K, V]] = {
    partitionedIterator.flatMap(pair => pair._2)

If you want to use C , then you should implement Writer with C as, 如果你想使用C ,那么你就应该实现WriterC为,

with Writer[K, C] {

Try replacing Iterator in your scala class with java.util.Iterator as the scala Iterator and the java Iterator are different. 尝试将scala类中的Iterator替换为java.util.Iterator,因为scala Iterator和Java Iterator是不同的。

private class ExternalWriter[K, V, C]
  extends Logging
  with Writer[K, V] {

    override def iterator(): java.util.Iterator[Product2[K, C]] = {
        partitionedIterator.flatMap(pair => pair._2)
  }
}

The above would be the modified code. 上面是修改后的代码。

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

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