将可变java类转换为不可变scala类

时间:2015-06-12 16:12:53

标签: scala immutability

我有一个类似于这样的类

class OutputFile(name: String, index: Int = 0){
  val localFile = File.createTempFile(name, ".gz")
  localFile.deleteOnExit()
  val localFileOut =new FileOutputStream(localFile)
  private[this] var bytesWritted: Int = 0
  def write(line: Bytes): OutputFile = {
    if(bytesWritten > SOMESIZE) flush //this function uploads the file to a different location and closes the localfile and localFileOut
    try{
      writeLine(line) //this writes the line to the localfile
      this
    }catch{
      //If the file had been closed by flush create a new object
      case IOException => 
        val outFile = new OutputFile(name, index+1)
        outfile.write(line)
        outfile
    }
    //Other functions like flush and writeLine
  }

但是现在我不能将这个对象用于不可变的。来自java背景,我很难将此类转换为不可变的样式。在java代码中,我们可以使用全局变量作为输出流,并在需要时对其进行更改。

是否有一些更好的方法,我肯定缺少实现这样的方案。

1 个答案:

答案 0 :(得分:0)

要使OutputFile的工作流不可变,每次调用都必须返回一个新的不可变实例,而不仅仅是交换文件的调用:

object OutputFile {
  def apply(name: String): OutputFile = {
    new OutputFile(name, newStream(name), 0)
  }

  private def newStream(name: String): FileOutputStream = {
    val localFile = File.createTempFile(name, ".gz")
    localFile.deleteOnExit()
    new FileOutputStream(localFile)
  }
}

class OutputFile(name: String, stream: FileOutputStream, bytesWritten: Int) {

  val THRESHOLD = 1000000

  def write(line: Bytes): OutputFile = write(line, 1)

  private def write(line: Bytes, attempt: Int): OutputFile = {
    try {
      val written = writeLine(line) //this writes the line to the localfile
      if (written > THRESHOLD) {
        flush
        new OutputFile(name, OutputFile.newStream(name), 0)
      } else new OutputFile(name, stream, written)
    } catch {
      case x: IOException =>
        if (attempt > 3) throw x
        else write(line, attempt + 1)
    }
  }

  // returns bytesWritten + length of line
  private def writeLine(line: Bytes): Int = ???

  // uploads file, closes and deletes it
  private def flush: Unit = ???
}

我添加了一个伴随对象OutputFile,以便实际的构造函数是新的不可变实例的构造函数,并抽象出新流的开头。

每次写入调用都会创建一个新的OutputFile并跟踪已写入当前文件的字节数。达到THRESHOLD后,将刷新文件并返回带有新流的新实例。 IOException不再负责触发新文件(当我们知道我们已经刷新时就完成了),而是重试最多3次。

最后要提醒的是:这个类本身仍然是有状态的,因为它确实处理了文件I / O.虽然这试图假装没有状态,但它假设在单个实例上写入永远不会两次。