Reputation: 14309
I found the following definition in Scala Saddle and just want to be sure I understood it correctly. There is an object defining an implicit function that exposes some HDF5 I/O functionality to the Frame type so that the writeHdfFile
function becomes available to any 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
}
However, I have never seen the = new {
syntax before. Does it mean it is creating and returning a new function each time? why would that make more sense as opposed to simply doing = {
Upvotes: 0
Views: 96
Reputation: 7845
it is creating an anonymous class. You can learn more about anonymous classes in scala here
Upvotes: 2
Reputation: 4296
Its a new anonymous class with 1 function.
In this case its used to provide syntax to the frame: Frame[RX, CX, T]
.
With this helper class in scope you can write.
frame.writeHdfFile(...)
Without this technique you would need to write.
writeHdfFile(frame, ...)
Normally this is done with a implicit class rather than a implicit def like that.
One benefit of this technique is that you can add helper methods to a class without changing them directly. Note how writeHdfFile
is not defined on Frame
This is done pretty similar to how type classes are implemented in scala.
Upvotes: 5