progs/detokenise.scala
changeset 645 30943d5491b6
parent 644 b4f5714485e1
child 686 05cfce0fdef7
--- a/progs/detokenise.scala	Wed Oct 02 02:09:48 2019 +0100
+++ b/progs/detokenise.scala	Wed Oct 02 14:05:36 2019 +0100
@@ -10,6 +10,7 @@
 object Detokenise {
 
 import java.io._
+import scala.util._ 
 
 abstract class Token extends Serializable 
 case object T_SEMI extends Token
@@ -21,16 +22,16 @@
 case class T_KWD(s: String) extends Token
 case class T_STR(s: String) extends Token
 
-def deserialise[T](fname: String) : T = {
-  val in = new ObjectInputStream(new FileInputStream(fname))
-  val data = in.readObject.asInstanceOf[T]
-  in.close
-  data
+def deserialise[T](fname: String) : Try[T] = {
+  import scala.util.Using
+  Using(new ObjectInputStream(new FileInputStream(fname))) {
+    in => in.readObject.asInstanceOf[T]
+  }
 }
 
 def main(args: Array[String]) = {
   val fname = args(0)
-  val tks = deserialise[List[Token]](fname)
+  val tks = deserialise[List[Token]](fname).getOrElse(Nil)
   println(s"Reading back from ${fname}:\n${tks.mkString("\n")}")  
 }