我想在我的程序中使用 Java OOP 的代码结构化优势和 Scala 函数式方法的优势,以实现具有递归的算法。
如何在我的应用程序中编写 Java 和 Scala 功能?
实际上,我的意思是如何将几个 Scala 类连接到我的 Java Web 应用程序?
这是我最近正在研究的一个简短示例:
在 Alfresco 中,使用以下 Java 接口/类定义了一个 webscript(类似于类固醇的 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 webscripts 定义一个基类,引入日志记录和一些样板代码作为 Scala 特征:
abstract class WebscriptBase extends AbstractWebScript with ServiceBase with Logging {
// "ServiceBase" and "Logging" are two Scala traits
}
我定义了一个 webscript 类,覆盖了原始 Java 接口中声明的抽象方法:
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 语法的转换!
在 Scala 中编写代码并不能防止 StackOverflowError。除非您的递归方法可以编写为尾递归,否则 Scala 编译器实际上可能会将其编译为循环。
像这样的简单函数会导致 StackOverflowError
def f(i: Long):Long = i match {
case 1 => 1
case n => f(n-1) + n
}
当我在 Scala REPL 中进行测试时,6095
足以将其击垮。
尾递归版本可以像
def f(i: Long):Long = {
@tailrec
def ff(ii: Long, ans: Long): Long = ii match {
case 0 => ans
case n => ff(ii-1, ans + n)
}
ff(i, 0)
}