Should I use Unit or leave out the return type for my scala method?

ScalaVoidReturn Type

Scala Problem Overview


I am not sure what the difference is between specifying Unit as the return type of my scala method or leaving out the return type altogether. What is the difference?

Can anyone please advise?

Scala Solutions


Solution 1 - Scala

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 [tag: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 - Scala

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 - Scala

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbalteoView Question on Stackoverflow
Solution 1 - ScalaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - ScalaHeiko SeebergerView Answer on Stackoverflow
Solution 3 - ScalaDaniel C. SobralView Answer on Stackoverflow