views:

96

answers:

2

Hi Guys.

I'm playing with serialisation, and hitting an issue with typing when reading back in from a file.

My current plan of action is to use a filename prefix to suggest the correct type, then base the deserialisation on that type. (This may well be a "Very Bad Idea", so any suggestions otherwise would be most gratefully received!)

Essentially, I want to write an object to a file, then, at some point later, read the file back in to an object of the correct type.

The following is something like what I want to use:

def readPatch(name:String): Patch = {
    // split name at tilde, prefix gives type
    val List(typeCode, filename) = List.fromString(name,'~')

    val patchClass = typeCode match {
        case "cfp" => CreateFilePatch.getClass
        case "dfp" => DeleteFilePatch.getClass
        case "cp" => ChangePatch.getClass
    }

    val inStream = new ObjectInputStream(new FileInputStream(filename))

    inStream.readObject().asInstanceOf[patchClass]
}

but I think am not able to due to Types not being Objects. I'm getting an error of "not found: type patchClass" when trying this code.

Could anyone suggest ideas?

+2  A: 

Try this:

patchClass.cast(inStream.readObject())
Alex Cruise
+4  A: 

As a quick workaround you can use the type knowledge that you already have directly in the match block.

def readPatch(name:String): Option[Patch] = {
  val List(typeCode, filename) = List.fromString(name,'~')
  val inStream = new ObjectInputStream(new FileInputStream(filename))
  val obj      = inStream.readObject()

  typeCode match {
    case "cfp" => Some(obj.asInstanceOf[CreateFilePatch])
    case "dfp" => Some(obj.asInstanceOf[DeleteFilePatch])
    case "cp"  => Some(obj.asInstanceOf[ChangePatch])
    case _     => None
  }
}
Don Mackenzie
Nice, that works!I'm not sure I'm approaching the problem the best way, but for now this'll do; thanks!
owst