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.
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.
If it's redundant, leave it out. The less clutter, the easier it is to read.
val service = new EventResponder {
def respond(message: String) = ""
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With