猿问

如何将 Scala 特征转换为 Java 类?

我尝试将一些 Scala 源代码转换为 Java 源代码。但我面临一些麻烦。以下是 Scala 源代码。


trait Reader {

  def read(name: String): String = {

    //some codes are here.....

  }

}


trait FileInputBase {

  def getFormat(path: String): String = {

    //some codes are here.....

  }

}


case class FileStreamInput(name: String, path: String) extends Reader with FileInputBase {

  def read(name: String): String = {

    //some codes are here.....

  }


  var format = getFormat("joseph") 

}

我将这些 Scala 代码转换为 Java 源代码,如下所示,


class Reader {

  public String read(String name) {

    // some java codes are here

  }

}


interface FileInputBase {

  public String getFormat(String path) {

    // some java codes are here

  }

}

我做了java类


public class FileStreamInput extends Reader implements FileInputBase {

  ....

}

但这些Java代码根本不起作用。我是 Scala 语言的初学者。


MM们
浏览 156回答 1
1回答

翻阅古今

你可以尝试这样的事情:public interface Reader {  default String read(String name) {    return "reading from " + name;  }}public interface FileInputBase {  default String getFormat(String path) {    return "Format of " + path;  }}public class FileStreamInput implements Reader, FileInputBase {  private String path;  private String name;  public FileStreamInput(String path, String name) {    super();    this.path = path;    this.name = name;  }  public String read(String name) {    return "FileStreamInput: reading from " + name;  }  public String getPath() {    return path;  }  public void setPath(String path) {    this.path = path;  }  public String getName() {    return name;  }  public void setName(String name) {    this.name = name;  }  public String getFormat() {    return getFormat(path);  }  public static void main(String[] args) {    FileStreamInput input = new FileStreamInput("Alice", "/home/alice");    System.out.println("format: " + input.getFormat());  }}
随时随地看视频慕课网APP

相关分类

Java
我要回答