Others have perfectly explained the differences between the different declarations:
def foo: Boolean = true // explicitly declare the return type
and
def foo = true // let the compiler to implicitly infer Boolean
That being said, I have to warn you against
def foo { }
This is called procedure-syntax, and you should never use it, as it's has been already deprecated (since Oct 29, 2013), although you'll get a deprecation warning only under the -Xfuture
flag.
Whenever you have to declare a method returning Unit
(which you should avoid as much as possible, since it means you're relying on side-effects), use the following syntax
def foo: Unit = { }
Also, as a personal advice, explicitly annotating return types makes your code often more readable and helps you in catching errors early. You know what the function should return, so explicitly annotating the type allows the compiler to check that the implementation returns an appropriate value, right at the declaration position (if you use the function you will catch an error eventually, but perhaps far from where the error really is).
Also, when declaring an abstract member, you'd better also annotate the types
trait {
def foo
}
is legal, but the type of foo
is automatically inferred to be Unit
, which almost never what you want.
Instead, do
trait {
def foo: Boolean
}
=
between closing)
of args and opening{
of method body) is (silently) deprecated, it is not true for everyone that the=
is "easy to overlook". Personally I find: Unit =
easy to overlook as compared to a method that returns something useful; it doesn't jump out at me as something that will surely cause side effects. That said, the no-equals syntax is supposed to go away eventually, so perhaps best not to get too fond of it. – Wakefield