To answer your questions in order:
f2andf5()returnUnitbecause scala takes anydefwithout an “=” to be a function that returnsUnit, regardless of what the last item in a block is. This is a good thing, since otherwise it would not be rather verbose to define a function that does not return anything.println(f5())is valid, even though it returnsUnitbecause in scalaUnitis a valid object, though admittedly not one you can instantiate.Unit.toString()is a valid, if not generally useful, statement, for example.- Not all the versions that print out
10are the same. Most importantly,f7,f8, andf9are actually functions that return functions that return10, rather than returning10directly. When you declaredef f8 = () => {10}, you are declaring a functionf8that takes no arguments and returns a function that takes no arguments and returns a single integer. When you invokeprintln(f8)thenf8dilligently returns that function to you. When you callprintln(f8())it returns the function, then immediately invokes it. - The functions
f1,f3,f4, andf6are all essentially equivalent in terms of what they do, they vary only in terms of style.
As “user unknown” indicates, the braces are only important for scoping purposes and do not make any difference in your use case here.