Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 842
balteo Avatar asked Feb 27 '12 08:02

balteo


People also ask

What does it mean that a function returns Unit in Scala?

In Scala we use the Unit return type to indicate "no return value." This is a "void" function. The void keyword is not used. Return An empty "return" statement can be used in a method that returns a Unit type. This means "no value."

Does Scala function need return?

The Scala programming language, much like Java, has the return keyword, but its use is highly discouraged as it can easily change the meaning of a program and make code hard to reason about.

What is the return type of a procedure in Scala?

If you don't specify any return type of a function, default return type is Unit which is equivalent to void in Java. = : In Scala, a user can create function with or without = (equal) operator. If the user uses it, the function will return the desired value.

What is Unit in Scala?

Unit is a subtype of scala. AnyVal. There is only one value of type Unit , () , and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void . Source Unit.scala.


1 Answers

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.

like image 65
Tomasz Nurkiewicz Avatar answered Oct 12 '22 00:10

Tomasz Nurkiewicz