Returning the lazy val to 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 basically governs what I want to do to return a function that opens a stream from a file when it is 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 I would really like to return a lazy val that flows from the file after its link, for example:

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 the client code can consider it as a value, not a function?

+5
source share
1 answer

You cannot "return the lazy shaft" - the client code must declare it lazy. If you do not want the client to declare a lazy val, you could return a shell:

class LazyWrapper[T](wrp: => T) {
  lazy val wrapped: T = wrp
}

object LazyWrapper {
  implicit def unboxLazy[T](wrapper: LazyWrapper[T]): T = wrapper.wrapped
}

And then:

def streamer(path: String) = new LazyWrapper(new FileReader(path))

equals, hashCode .. LazyWrapper, .

+15

All Articles