Using a variable in finally block

前端 未结 4 1095
忘掉有多难
忘掉有多难 2021-01-22 10:29

Here is code in Scala:

def write() = {
    try {
      val out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)))
      out.println(\"123\")
          


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-22 11:34

    Or just:

    val is = new FileInputStream(file)
    val result = try {
        // do stuff
    } finally {
        is.close()
    }
    

    Because there's no way is can be null.

    In your question code, just move val out outside try block. That way it will be identical to what Java AutoCloseable does, except for null case. But in Scala you don't have to deal with nullables.

提交回复
热议问题