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

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.

Leave a Comment