题
我试图编写一种简单的助手方法,该方法接收可以关闭的东西,并且一些接收前者的功能,并确保执行功能后“可闭合”是关闭的。
例如,我想这样使用:
closing(new FileOutputStream("/asda"))(_.write("asas"))
我的印象是
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]不符合方法关闭的类型参数bounds [t <:anyref {def {def collect:unit}
有什么想法吗?
解决方案
你需要写
def closing[T <: { def close() }]
空括号和无括号的方法之间的Scala有差异。
其他提示
类型范围很棘手。特别是,除了参数本身之外,Scala还跟踪参数列表的数量。尝试这些!
class A { def f = 5 }
class B { def f() = 5 }
class C { def f()() = 5 }
def useA[X <: { def f: Int }](x: X) = x.f
def useB[X <: { def f(): Int }](x: X) = x.f
def useC[X <: { def f()(): Int}](x: X) = x.f
useA(new A) // This works, but what other combinations do?
就您而言,您想要
def closing[T <: { def close() }] ...
PS如果您真的打算经常使用此功能,那么您可能还应该玩
class D extends B { override def f = 6 }
class E extends A { override def f() = 6 }
看看哪个 use
您需要在每种情况下使用。
不隶属于 StackOverflow