Should I use Unit or leave out the return type for my scala method?
Solution 1:
Implicit Unit
return type:
def f() {println("ABC")}
Explicit Unit
return type:
def g(): Unit = {println("ABC")}
Return type inferred from the last method expression, still Unit
because this is the type of println
, but confusing:
def h() = println("ABC")
All the methods above are equivalent. I would prefer f()
because the lack of =
operator after method signature alone is enough for me. Use explicit : Unit
when you want to extra document the method. The last form is confusing and actually treated as a warning in intellij-idea.
The =
operator is crucial. If it is present it means: "please return whatever the last statement returns" in method body. Obviously you cannot use this syntax for abstract
methods. If it is not, Unit
is assumed.
Solution 2:
The special syntax for procedures (methods returning Unit) was a mistake. Don't use it. It is confusing and dangerous for beginners with a Java/C(++) background. And it is a unnecessary special treatment. Always use the equal sign, with and without type inference (the latter should only be used for private members):
def foo(): Unit = someCodeReturningUnit()
private def bar() = someCodeReturningUnit()
Solution 3:
The Scala community is divided about it. On the one hand, not using explicit return types means you can easily forget the =
sign, which results in errors that are often annoying to track. On the other hand, Unit
-returning methods having a different syntax puts them in a separate category, which pleases some people.
Personally, I'd rather this syntax would go away -- the errors resulting from missing =
are annoying to track. But it's not even deprecated, so I'd rather take advantage of it than just suffer the problems of its existence.
So, use whatever you wish. There's going to be people criticizing your choice either way, and people praising it either way.