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?
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."
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With