【问题标题】:Why this structural type bound does not work as expected?为什么这种结构类型绑定不能按预期工作?
【发布时间】:2011-01-24 21:37:57
【问题描述】:

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

例如,我想这样使用它:

  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>

有什么想法吗?

【问题讨论】:

    标签: scala structural-typing


    【解决方案1】:

    你需要写

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

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

    【讨论】:

    • FileOutputStream.write 显然不能接受字符串。在字符串上调用getBytes()
    【解决方案2】:

    类型界限很棘手。特别是,除了参数本身之外,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() }] ...
    

    附:如果你真的打算经常使用它,你可能也应该玩

    class D extends B { override def f = 6 }
    class E extends A { override def f() = 6 }
    

    看看你需要在每种情况下使用哪个use

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多