gpt4 book ai didi

java - 这是将 Java 接口(interface)转换为 Scala 的正确方法吗?

转载 作者:行者123 更新时间:2023-11-29 06:04:25 25 4
gpt4 key购买 nike

我开始学习Scala,我会做一个简单的交叉编译器。

我将支持一小组指令,例如打印。

注意:代码片段未经测试或编译。
以下是我会在 JAVA 中执行的操作。

public interface Compiler{
String getPrintInstruction();
}

public class JavaCompiler implements Compiler{
public String getPrintInstruction(){
return "System.out.print(arg0);"
}
}

public class ScalaCompiler implements Compiler{
public String getPrintInstruction(){
return "print(arg0);"
}
}

下面的代码段是正确的“Scala 方式”吗?

trait Compiler {
var printInstruction: String
}
class JavaCompiler extends Compiler {
var printInstruction = "System.out.print(arg0);"
}
class ScalaCompiler extends Compiler {
var printInstruction = "print(arg0);"
}

编辑:

我会将我的第二个问题移至新线程。

最佳答案

对于 1:1 映射,那些 var 应该更改为 def

trait Compiler {
def printInstruction: String
}

class JavaCompiler extends Compiler {
def printInstruction = "System.out.print(arg0);"
}

class ScalaCompiler extends Compiler {
def printInstruction = "print(arg0);"
}

def 声明了一个方法。当您不提供实现时,它就变成了抽象方法。

编辑:

此处使用的技术是有效且有用的技术。或者,您可以使用以下两种技术之一来为您的问题建模。

1) 受歧视的工会。 (又名求和类型。)

引用this excellent article了解这个概念。这就是您的示例以这种方式建模时的样子:

sealed trait Compiler {
def printInstruction: String = this match {
case JavaCompiler => "System.out.print(arg0);"
case ScalaCompiler => "print(arg0);"
}
}

case object JavaCompiler extends Compiler
case object ScalaCompiler extends Compiler

2) 类型类模式。

Here是 Daniel Sobral 关于这个主题的一篇很棒的文章。您可以通过谷歌搜索术语类型类、模式、Scala、隐式等来挖掘更多信息。如果问题使用类型类模式建模,您的代码可能看起来像这样:

trait Compiler[C] {
def printInstruction(c: C): String
}

case object JavaCompiler

implicit object JavaCompilerIsCompiler extends Compiler[JavaCompiler.type] {
def printInstruction(c: JavaCompiler.type): String = "System.out.print(arg0);"
}

case object ScalaCompiler

implicit object ScalaCompilerIsCompiler extends Compiler[ScalaCompiler.type] {
def printInstruction(c: ScalaCompiler.type) = "print(arg0);"
}

对于您的问题,原始方法和可区分的联合方法似乎是最好的建模解决方案。

关于java - 这是将 Java 接口(interface)转换为 Scala 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9033253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com