如何在Java中使用Scala隐式类 [英] How to use Scala implicit class in Java

查看:95
本文介绍了如何在Java中使用Scala隐式类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RecordService API的Scala Implicit类,我想在Java文件中使用它.

I have a Scala Implicit class from RecordService API, which i wanted to use in Java file.

package object spark {

   implicit class RecordServiceContext(ctx: SparkContext) {
     def recordServiceTextFile(path: String) : RDD[String] = {
      new RecordServiceRDD(ctx).setPath(path)
          .map(v => v(0).asInstanceOf[Text].toString)
    }
  }

}

现在,我正尝试使用下面的import将其导入Java文件中.

Now i am trying to import this in a Java file using below import.

import com.cloudera.recordservice.spark.*;

但是我无法使用sparkContext中的recordServiceTextFile("path").

But i am not able to use recordServiceTextFile("path") from sparkContext.

在Scala中,导入几乎没有什么不同,并且可以正常工作.

In Scala the import is little different and its working.

推荐答案

这是包对象中隐式类的简单定义

Here is simple definition of implicit class in package object

package object spark {
  implicit class Ext(param: Int) {
    def a = param + 1
  }
}

这是从Java中使用它的方法

and here is how you can use it from java

public class Test {
    public static void main(String[] args) {
        spark.package$.MODULE$.Ext(123).a();
    }
}

因此,您基本上可以将 RecordServiceContext 用作包装 SparkContext 并添加一个可以调用的额外方法的方法.那是对隐式类的优化.

so you can basically use RecordServiceContext as a method that wraps your SparkContext and adds an extra method that you can call. That is optimization for implicit classes.

那将是这样的:

SparkContext c = ???
RDD<String> rdd = com.cloudera.recordservice.spark.package$.MODULE$.RecordServiceContext(c)
   .recordServiceTextFile("asdf");

这篇关于如何在Java中使用Scala隐式类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆