Java:连接Scala模块

标签 java scala

我想在我的程序中利用 Java OOP 的代码结构化优势和 Scala 函数式方法的优势来实现递归算法。

如何在我的应用程序中组合 Java 和 Scala 功能?

实际上我的意思是如何将几个 Scala 类连接到我的 Java Web 应用程序?

最佳答案

这是我最近正在研究的一个简短示例:

在 Alfresco 中,使用以下 Java 接口(interface)/类定义一个网页脚本(有点像 servlet,实际上现在是 Spring 框架的一部分):

public interface WebScript
{
  /**
 * Execute the Service
 * 
 * @param req   WebScriptRequest representing the request to this service
 * @param res   WebScriptResponse encapsulating the result of this service
 * 
 * @throws IOException
 */
public void execute(WebScriptRequest req, WebScriptResponse res)
    throws IOException;
}

现在我可以轻松地为 Scala 网页脚本定义一个基类,引入日志记录和一些样板代码作为 Scala 特征:

abstract class WebscriptBase extends AbstractWebScript with ServiceBase with Logging {
   // "ServiceBase" and "Logging" are two Scala traits 
}

我定义了一个webscript类,覆盖了原始Java接口(interface)中声明的抽象方法:

class SampleWebscript extends WebscriptBase {

  override def execute(req: WebScriptRequest, response: WebScriptResponse): Unit = {

  try {
    response.setContentType(MIMETYPE_JSON)
    val writer = new PrintWriter (response.getWriter)
    writer.println("{'Hopp':'Topp'}")
  }

 }

 }

最后,我在 Spring bean 配置中使用此类(用 Scala 编写):

<bean id="webscript.de.treufuss.dedup.helloWorld.get" parent="webscript" class="de.treufuss.alfresco.service.dedup.webscript.SampleWebscript">
</bean>

请注意,“SampleWebscript”类看起来和感觉就像一个普通的 java 类 - 唯一的魔力是从 Java 的方法签名转换为 Scala 语法!

关于Java:连接Scala模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19528677/

相关文章:

java - 从 float 中删除数字标记并转换为整数

Java InputVerifier查找导致 "focus lost"的组件

java - 来自 hikaricp 连接池的连接对象

scala - 你如何在 sbt 中编写任务?

Scala 在 match case 语句中使用带有或语法的正则表达式

java - Google App Engine 应用程序实例回收和响应时间

java - 使用字符串名称访问Java对象的成员变量

scala - 在线应用部分应用函数的问题

oop - 什么是开放递归?

scala - Scala 中的类型级编程