Question

Possible Duplicate:
scala: 'def foo = {1}' vs 'def foo {1}'

Why is it that when defining the method main in Scala, there is no need to use a =?

Example:

def main(args:Array[String]) {
    ...

But if one wants to define another function it requires it.

def main(args:Array[String]) **=** {
...

Can someone explain this syntax?

Was it helpful?

Solution

In Scala, the equals sign in a method declaration tells the compiler that the method returns something. If no equals sign appears, then the compiler knows that that the method doesn't return anything. This is equivalent to a void method in Java. In Scala, returning nothing is the same as returning Unit.

scala> def noEquals(x: Int) { x + 1 }
noEquals: (x: Int)Unit

scala> val y = noEquals(5)
y: Unit = ()

Compare to an example in which the equals sign appears:

scala> def hasEquals(x: Int) = { x + 1 }
hasEquals: (x: Int)Int

scala> val z = hasEquals(5)
z: Int = 6

In Java, the main method doesn't return anything (it's declared as void, as in public static void main(String[] args)). Thus, the Scala version leaves off the equals sign.

Note also that you can write an main method with an equals sign, as long as the method returns Unit (though this would be against convention). Also, an equals sign is not "required" for other methods... just those that need to return things. It's perfectly acceptable (and appropriate) to leave off the equals sign if you are writing a method that doesn't return anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top