加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么这个结构类型绑定不能按预期工作?

发布时间:2020-12-16 18:25:59 所属栏目:安全 来源:网络整理
导读:我正在尝试编写一个简单的辅助方法,它接收可以关闭的东西和一些接收前者的函数,并确保在执行函数后关闭“closeable”. 例如,我想像这样使用它: closing(new FileOutputStream("/asda"))(_.write("asas")) 我的意思是 object Helpers { def closing[T : { de
我正在尝试编写一个简单的辅助方法,它接收可以关闭的东西和一些接收前者的函数,并确保在执行函数后关闭“closeable”.

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

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

}

编译器抱怨:

inferred type arguments
[java.io.FileOutputStream] do not
conform to method closing’s type
parameter bounds [T <: AnyRef{def
close: Unit}]

有什么想法吗?

解决方法

你需要写

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

Scala与空括号的方法和没有括号的方法之间存在差异.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读