Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

methods

scala

what is going on in each of these forms of defining foo?:

scala> def foo = {1}
foo: Int

scala> foo
res2: Int = 1

But:

scala> def foo {1}
foo: Unit

scala> foo

scala>
like image 226
IttayD Avatar asked Nov 02 '09 15:11

IttayD


2 Answers

See also this question and answer on SO:

In Scala if a method declaration does not have an equal sign before its body, the compiler infers that the result type will be Unit

Basically declaring a function with no = means that the function returns Unit and the compiler inserts a () for you at the end. A function which should return a non-Unit value must be declared with the = notation (although of course the compiler can infer the return-type from the expression's type).

like image 65
oxbow_lakes Avatar answered Nov 08 '22 12:11

oxbow_lakes


found this in http://anyall.org/scalacheat/:

//[bad!] 
def f(x: Int) { x*x } //hidden error: without = it's a Unit-returning proc; causes havoc 
like image 2
IttayD Avatar answered Nov 08 '22 12:11

IttayD