在 Scala 中返回一个惰性 val
我有一个如下所示的函数:
package org.thimblr.io
import java.io._
object Local {
def streamer(path: String) = () => new FileReader(path)
}
这基本上管理了我想要做的事情,即返回一个在调用时从文件中打开流的函数。所以客户端代码可以这样做:
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
但我真正想要的是返回一个惰性val,一旦引用它就从文件中流出来,如下所示:
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
是否可以做这样的事情,返回一个惰性val,以便客户端代码可以将其视为一个值而不是一个函数吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能“返回一个惰性值”——客户端代码必须将其声明为惰性值。如果您不想强制客户端声明惰性 val,您可以返回一个包装器:
然后:
您可以进一步转发
equals
、hashCode
等。如果您需要的话,可以添加到 LazyWrapper 中的包装对象。You can't “return a lazy val” — client code must declare it as lazy. If you don't want to force the client to declare a lazy val, you could return a wrapper instead:
And then:
You could further forward
equals
,hashCode
, etc. to the wrapped object inLazyWrapper
if you need those.