Nine ways to define a method in Scala?

To answer your questions in order:

  • f2 and f5() return Unit because scala takes any def without an “=” to be a function that returns Unit, 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 returns Unit because in scala Unit is 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 10 are the same. Most importantly, f7,f8, and f9 are actually functions that return functions that return 10, rather than returning 10 directly. When you declare def f8 = () => {10}, you are declaring a function f8 that takes no arguments and returns a function that takes no arguments and returns a single integer. When you invoke println(f8) then f8 dilligently returns that function to you. When you call println(f8()) it returns the function, then immediately invokes it.
  • The functions f1,f3,f4, and f6 are 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)