Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala style for empty class parameter lists

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.

like image 843
njlarsson Avatar asked Oct 26 '11 13:10

njlarsson


3 Answers

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.

like image 126
0__ Avatar answered Nov 19 '22 21:11

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) = ""
}
like image 34
Luigi Plinge Avatar answered Nov 19 '22 19:11

Luigi Plinge


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.

like image 37
jxstanford Avatar answered Nov 19 '22 21:11

jxstanford