Scala类继承自Java的泛型类

6

我试图用Scala编写一个Hadoop Mapper类。作为起点,我参考了《Hadoop权威指南》中的一个Java示例,并尝试将其移植到Scala。

原始的Java类继承自org.apache.hadoop.mapreduce.Mapper

public class MaxTemperatureMapper
    extends Mapper<LongWritable, Text, Text, IntWritable>

并覆盖该方法

public void map(LongWritable key, Text value, Context context)
    throws IOException, InterruptedException

这个方法被调用并正常工作(我使用单元测试进行了测试,然后使用yarn运行它)。

我尝试将其转换为Scala:

class MaxTemperatureMapperS extends Mapper[LongWritable, Text, Text, IntWritable]

然后是这个方法。
@throws(classOf[IOException])
@throws(classOf[InterruptedException])
override def map(key: LongWritable, value: Text, context: Context): Unit = 
{
    ...
}

但是Scala编译器会报错:

error: method map overrides nothing.

我认为在Scala和Java中这两种方法的签名相同,但显然我漏掉了什么。你能给我一些提示吗?

2个回答

7
有时候,让你的集成开发环境(IDE)为你服务是最好的方法:
class Test extends Mapper[LongWritable, Text, Text, IntWritable] {
  override def map(key: LongWritable, value: Text, context: Mapper[LongWritable, Text, Text, IntWritable]#Context): Unit = ???
}

在这种情况下,问题在于上下文类“生活”在Mapper类内部,因此您需要使用#语法。

1
所以编译器找到的“Context”可能是其他作用域中的某个类!这很有道理。非常感谢! - Giorgio
现在它可以工作了。我已经将整个Hadoop示例应用程序从Java移植到Scala,并且运行非常顺畅。非常感谢。 - Giorgio

0
提供参考代码,用于在Scala中覆盖Mapper和Reducer类中的map和reduce方法。
Mapper示例:
class MaxTemperatureMapper extends Mapper[LongWritable, Text, AvroKey[Integer], AvroValue[GenericRecord]] {

  val parser = new NcdcRecordParser()
  val record = new GenericData.Record(AvroSchema.SCHEMA)

  @throws(classOf[IOException])
  @throws(classOf[InterruptedException])
  override def map(key: LongWritable, value: Text, context:Mapper[LongWritable, Text, AvroKey[Integer], AvroValue[GenericRecord]]#Context) = {

Reducer 示例:

class MaxTemperatureReducer extends  Reducer[AvroKey[Integer],AvroValue[GenericRecord],AvroKey[GenericRecord],NullWritable]{

  @throws(classOf[IOException])
  @throws(classOf[InterruptedException])
  override def reduce(key:AvroKey[Integer],values:java.lang.Iterable[AvroValue[GenericRecord]],
      context:Reducer[AvroKey[Integer],AvroValue[GenericRecord],AvroKey[GenericRecord],NullWritable]#Context) = {


请勿发布代码的图像,请使用块代码格式将代码复制到问题中:https://stackoverflow.com/help/how-to-ask - borchvm
已根据要求进行编辑。谢谢。 - Pramod Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接