在 Scala 中返回一个惰性 val

发布于 2024-11-04 23:04:09 字数 814 浏览 2 评论 0原文

我有一个如下所示的函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓦然回首 2024-11-11 23:04:22

你不能“返回一个惰性值”——客户端代码必须将其声明为惰性值。如果您不想强制客户端声明惰性 val,您可以返回一个包装器:

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

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

然后:

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

您可以进一步转发 equalshashCode 等。如果您需要的话,可以添加到 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:

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))

You could further forward equals, hashCode, etc. to the wrapped object in LazyWrapper if you need those.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文