为什么这种结构类型绑定不能按预期工作?
我正在尝试编写一个简单的辅助方法,该方法接收可以关闭的内容和一些接收前者并确保“可关闭”在执行该函数后关闭的函数。
例如,我想像这样使用它:
closing(new FileOutputStream("/asda"))(_.write("asas"))
我的 impl 是
object Helpers {
def closing[T <: { def close }](closeable: T)(action: T => Unit): Unit =
try action apply closeable finally closeable close
}
但是当尝试编译这个简单的测试时:
object Test {
import Helpers._
closing(new FileOutputStream("/asda"))(_.write("asas"))
}
编译器抱怨:
推断类型参数 [java.io.FileOutputStream] 不 符合方法关闭的类型 参数范围 [T <: AnyRef{def 关闭:单位}]
有什么想法吗?
I'm trying to write a simple helper method that receives something that can be closed and some function which receives the former and ensures the "closeable" is closed after executing the function.
For example, I want to use it like this:
closing(new FileOutputStream("/asda"))(_.write("asas"))
My impl is
object Helpers {
def closing[T <: { def close }](closeable: T)(action: T => Unit): Unit =
try action apply closeable finally closeable close
}
But when trying to compile this simple test:
object Test {
import Helpers._
closing(new FileOutputStream("/asda"))(_.write("asas"))
}
The compiler complains with:
inferred type arguments
[java.io.FileOutputStream] do not
conform to method closing's type
parameter bounds [T <: AnyRef{def
close: Unit}]
Any ideas why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你需要写出
Scala 中带空括号的方法和根本不带括号的方法之间的区别。
You need to write
there is a difference in Scala between methods with empty parentheses and methods without parentheses at all.
类型界限很棘手。特别是,除了参数本身之外,Scala 还跟踪参数列表的数量。试试这些吧!
就你而言,你想要
P.S.如果您确实打算经常使用它,您可能还应该尝试一下
,看看在每种情况下您需要使用哪个
use
。Type bounds are tricky. In particular, Scala keeps track of the number of parameter lists in addition to the parameters themselves. Try these out!
In your case, you want
P.S. If you really plan on using this a lot, you probably ought also play with
and see which
use
you need to use in each case.