new和花括号的含义是什么(没有要创建的类型)?

Sky*_*ker 0 scala saddle

我在Scala Saddle中找到了以下定义,只是想确保我理解正确.有一个对象定义了一个隐式函数,它将一些HDF5 I/O功能暴露给Frame类型,以便该writeHdfFile函数可用于任何Frame:

object H5Implicits {
  /**
   * Provides enrichment on Frame object for writing to an HDF5 file.
   */
  implicit def frame2H5Writer[RX: ST: ORD, CX: ST: ORD, T: ST](frame: Frame[RX, CX, T]) = new {

    /**
     * Write a frame in HDF5 format to a file at the path provided
     *
     * @param path File to write
     * @param id Name of the HDF group in which to store frame data
     */
    def writeHdfFile(path: String, id: String) {
      H5Store.writeFrame(path, id, frame)
    }

  } // end new
}
Run Code Online (Sandbox Code Playgroud)

但是,我以前从未见过= new {语法.这是否意味着它每次都在创建并返回一个新函数?为什么这会更有意义而不是简单地做= {

Ste*_*hen 5

它是一个带有1个函数的新匿名类.

在这种情况下,它用于提供语法frame: Frame[RX, CX, T].

有了这个助手类,你可以编写.

frame.writeHdfFile(...)
Run Code Online (Sandbox Code Playgroud)

没有这种技术,你需要写.

writeHdfFile(frame, ...)
Run Code Online (Sandbox Code Playgroud)

通常,这是通过隐式类而不是像这样的隐式def来完成的.

此技术的一个好处是您可以向类添加辅助方法而无需直接更改它们.注意如何writeHdfFile定义Frame

这与在scala中实现类型类的方式非常相似.