returning a lazy val in Scala

I have a function that looks like this:

package org.thimblr.io
import java.io._
object Local {
  def streamer(path: String) = () => new FileReader(path)
}

This manages basically what I want to do, which is to return a function that opens a stream from a file when it's called. So client code can do this:

val planStreamSource = Local.streamer("/home/someuser/.plan")
//...passes the function on to somewhere else
val planStream = planStreamSource()
val firstByte = planStream.read
//can now read from planStream

But what I'd really like is to return a lazy val that streams from a file once it's referenced, like this:

val planStream = Local.streamer("/home/someuser/.plan")
//...passes the val on to somewhere else, without opening the file for reading yet
val firstByte=planStream.read
//...such that planStream was only just opened to allow the read

Is it possible to do something like this, return a lazy val, so that client code can treat it as a value rather than a function?

5
задан traffichazard 30 April 2011 в 17:17
поделиться