1

I'm a bit confused about the Scala's recommended style of using the equal sign in Unit methods, which one is recommended?

 def withPrintWriter(file: File, op: PrintWriter => Unit) {
  val writer = new PrintWriter(file)
    try {
     op(writer)
    } finally {
     writer.close()
    }
 }

or

 def withPrintWriter(file: File, op: PrintWriter => Unit) = {
  val writer = new PrintWriter(file)
    try {
     op(writer)
    } finally {
     writer.close()
    }
 }
Alan Coromano
  • 24,958
  • 53
  • 135
  • 205
  • yep, the answer [there](http://stackoverflow.com/a/944791/618089) is pretty complete. If you do not intend to return results, prefer then notation **without** equal, or at least make it explicit that you do not return anything if you really want to use the =. `def withPrintWriter(file: File, op: PrintWriter => Unit): Unit = {}` – Mortimer Sep 09 '13 at 03:26

2 Answers2

3

There are strong opinions on both sides of the aisle, and no answer based in cognitive science for picking a style, aside from "whichever is easier on your eyes."

Usually, someone will say that one style jumps out at them and says, "I don't return anything useful."

However, there is a ticket to deprecate procedure syntax.

The fact that at ticket was opened or that Odersky sees the feature as subject to future deprecation is not definitive, of course.

Possibly, the debate evolves into: If I define a procedure, should I always specify the Unit result type? And the answer is probably yes. As a rule, you want to avoid inferring useless things.

But isn't it a hassle adding : Unit all the time? Yes, because procedures should stick out like the sore thumb they are. When all you have is a hammer, you always wind up with a sore thumb.

som-snytt
  • 39,429
  • 2
  • 47
  • 129
0

Yes of course, initially it is a bit confusing. I prefer using the Thumb rule like

If you are returning a value from a method, you may assign the return value to some other resource - Hence use "="

If you are not returning any value, you might just be computing/storing something or printing somethig - Hence forget about the "=".

ParoTech
  • 347
  • 2
  • 15