5

When creating an object without class parameters, I am having difficulty deciding whether I should include empty parentheses or not. A specific example: I am interfacing with existing Java code, and creating an object that implements an interface called EventResponder. Should I write:

val service = new EventResponder() {
  def respond(message: String): String = {
    return ""
  }
}

or

val service = new EventResponder {
  def respond(message: String): String = {
    return ""
  }
}

(Or, BTW, is there something else I should change here?)

Both seem to work, and as far as I can see, the Scala style guide does not have any recommendations for this. It talks about when to include empty parentheses for methods or arity-0, but that's not quite the same case.

2
  • 4
    You can (a) eliminate the return statement and just write "", (b) you can drop the curly braces around the result value and (c) you can omit the result type; it will be inferred by Scala. So the method would be def respond(message: String) = "" Commented Oct 26, 2011 at 14:03
  • 3
    Style aside, if you look at it from a maintenance perspective, leaving out the parens would allow you to switch EventResponder for a parameter less class or a trait at a later time without having to go back to this code and remove the parens. That's the only tangible benefit I can see.
    – huynhjl
    Commented Oct 26, 2011 at 14:27

3 Answers 3

6

You could use this to distinguish between a class (empty parens) and an interface (no parens) in Java world or a class (empty parens) and a trait (no parens) in Scala world.

You could also, analogous to methods, distinguish between instantiations with side-effects (empty parens) and those without (no parens). Although, I guess, a constructor should ideally never have side effects...

You could also distinguish between objects that carry state / are mutable (empty parens) and those that are immuable (no parens). Although, then, this conflicts with case classes which should be immutable but it is discouraged to use no parens here...

I personally tend to leave the empty parentheses away if possible. Two characters less, more readable.

1

Typically empty parens are used with methods to indicate that the method has side effects. It seems that if the constructor has side effects, it would be good form to follow the same guideline since you would basically be indicating that the apply method is going to have a side effect.

0

If it's redundant, leave it out. The less clutter, the easier it is to read.

val service = new EventResponder {
  def respond(message: String) = ""
}
1
  • but the rule for method invocation is different, so why not follow that here too? Commented Apr 19, 2017 at 20:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.