using Try monad
Mar. 12th, 2014 05:20 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
def using[T](file:File)(f: FileInputStream => T): Try[T] = Try { val in = new FileInputStream(file) (Try(f(in)), Try(in.close))._1 }.flatten def startsWith(prefix: Array[Byte])(file: File):Boolean = using (file) (in => prefix forall (in.read ==)) filter identity isSuccess
What happens here. I want to check if a file starts with these bytes (usually, "%PDF".getBytes).
I have function
using
that takes a file, then takes a function that converts a stream into something, opens the file, feeds the stream to the function, then always closes the file, returning a failure something went wrong.In startsWith I get a prefix and a file; on this file I call the function that reads the stream and compares its bytes with the bytes of prefix; the result will be Try[Boolean]; I filter it, so that Success(false) will turn into Failure; then I check if it's still a success.
Obvious and funny; and yes, we use Java io library here, unfortunately.