Do I have to specify "Unit" if a method does not return anything

What is the difference to have “Unit” than just leave it out?

And, for a method definition, this is what I have

def foo =
println(“aaa”)

Do I have to make it

def foo(): Unit = println(“aaa”)

In general, Scala will try to guess (“infer”) the types of many things, including the return types of defs.

That includes Unit, so you can totally write def foo = println("Hello").

However, I personally prefer to write the return types of functions that may be used by other pieces of code explicitly. That way, somebody can have a better idea of what the code does by just looking at the signature.

Hope it helps!

def foo(): Unit = ...

This is considered a best practice in Scala. We use the parentheses to show that this is a side-effecting method call, and the explicit return type annotation on all top-level methods for readability.

I just use

def foo() { … }

which is frowned on for some reason, but I don’t care. I’ll do it as long at the compiler allows it. Returning Unit just grates on me for some reason, like fingernails on a chalk board.

A while back I suggested a new keyword such as “proc” to clearly distinguish procedures from functions/methods that return something useful. But that is too radical I guess.

I do think ``def foo()``` proves is Unit, but that is by convention, so ultimately its up to you, but the compiler will still tell you if no Unit is found.

The missed opportunity was

def f(): _ = ...

which would be equivalent to

def f(): Unit = { ... ; () }

so that f is Unit and you never get a discarded value warning.

Nothing says “I don’t care” like an underscore. I’m bummed that the underscore.io store is all out of the moody tee that is black except for a single white _. Also, Single White _ should be the next sequel to Single White Female, in which Bridget Fonda plays a software designer. If underscore provides seed money to produce it as a diversity recruiting tool, it would be called Single: _* or possibly _: Singleton.

1 Like

That is called the ‘procedure syntax’ and it’s a deprecated syntax. It will be removed in Scala 3 (at latest) so it’s best not to have it in the codebase (will make things easier on yourself or whoever maintains the codebase after you).

To be honest I also don’t really see the problem with procedure syntax. It makes sense to me… But since it’s sort of deprecated, I’ve been trying to avoid it anyway recently.

it tends to trip up newcomers, and the advantage of having it is real, but limited.