Chris Bedford
Chris Bedford

Reputation: 2692

why can scala support this: new PrintWriter("filename") { write("file contents"); close }?

I have a question regarding a trick

new PrintWriter("/tmp/some.file") { write("file contents"); close }  

that I learned from this interesting post: Scala: write string to file in one statement

The technique works great (for test code), however I am a little puzzled about what is going on syntactically in Scala.

PrintWriter is a java class... but it looks like a code block is being passed to the print writer instance, and implicitly method calls are being executed on that instance. The PrintWriter java class definition has no apply() method that takes a function block.

So .. I'm puzzled as to what is going on visa vi Scala syntax

thanks !

Upvotes: 3

Views: 923

Answers (1)

rogue-one
rogue-one

Reputation: 11587

This works because you are effectively creating an anonymous object that extends PrintWriter class. the code write("file contents"); close is simply part of the constructor of this anonymous object.

scala> val writer = new PrintWriter("/tmp/some.file") { write("file contents"); close }
writer: java.io.PrintWriter = $anon$1@6c07add6

scala> writer.getClass.getName
res4: String = $anon$1

Upvotes: 6

Related Questions