4

我正在尝试编写一个简单的辅助方法,它接收可以关闭的东西和接收前者的函数,并确保在执行函数后关闭“可关闭”。

例如,我想像这样使用它:

  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] 不符合方法关闭的类型参数边界 [T <: AnyRef{def close: Unit}]

任何想法为什么?

4

2 回答 2

12

你需要写

def closing[T <: { def close() }]

在 Scala 中,带空括号的方法和完全不带括号的方法是有区别的。

于 2011-01-24T21:45:53.317 回答
7

类型界限很棘手。特别是,除了参数本身之外,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您需要在每种情况下使用哪个。

于 2011-01-24T21:47:23.127 回答