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

后端 未结 2 1745

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

scala> def foo = {1}
foo: Int

scala> foo
res2: Int = 1

But:



        
2条回答
  •  情歌与酒
    2020-12-06 17:55

    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).

提交回复
热议问题