In Scala, why do we need "=" when defining a method?
Next, we define that the scala function
def printName() : Any = { println ("vikrant") }
def printName() : Unit = { println ("vikrant") }
Is "=" just syntax or does it have a purpose? Asking this because I am allowed to skip this when I do not mention the return type, for example by following
def printName() { println ("vikrant") }
source to share
If the method returns Unit
, you can omit =
(known as procedure syntax), but this is very discouraging (it is deprecated and even discussed to be removed ). From the style guide in the docs :
Methods must be declared according to the following pattern:
def foo(bar: Baz): Bin = expr
Procedure syntax: Avoid procedure syntax as it tends to get confused for very little gain in brevity.
// don't do this
def printBar(bar: Baz) {
println(bar)
}
// write this instead
def printBar(bar: Bar): Unit = {
println(bar)
}
There is no difference in the generated bytecode. It's just syntactic sugar. See Section 4.6.3 of the Scala specification , which says:
There is a special syntax for procedures, that is, functions that return a
Unit
value()
. A procedure declaration is a function declaration where the result type is omitted. The result type is then implicitly terminatedUnit
.
So, it is compiled with the same code. This function has a warning associated with it if you use the option -Xfuture
:
warning: procedure syntax is outdated. Convert your procedure
foo
to a method by adding: Unit =
.
In Scala, every method returns a value (unlike other languages that have methods void
and do not return anything). Methods that void
in other languages often return Unit
in Scala (like your example printName
).
You can declare any method as returning Unit
, regardless of the value of the expression after =
. This language feature known as value drop is explained here.
source to share
Probably to fit in with a functional style. Scala seems to be as functional as possible, and curly braces are used to create an imperative block that departs from functionality. This is similar syntax for languages like Haskell, where you usually define functions instead of procedures.
The many ways it can be written are the result of a mixture of two very different paradigms.
source to share