Scala Function / Method Declaration

Now we know how to declare variables in Scala, Some of you now probably want try writing some methods. By default all variables passed in a method are mutable in Scala. Here are some rules for writing methods.

Rules for Scala Function / Method declaration

  • Return type declaration and semicolon are optional
  • Keyword return is optional
  • Every method parameter must be followed by type annotation
  • Curly braces are optional if the method just have the single line (Same as if else clause of Java)
  • Method names can contain characters like ‘.’ OR ‘*’ OR ‘+’ as Scala doesn’t have any native operators (all operators of Scala are methods)
  • Method with no parameters can be called without parentheses
  • Method with one parameter can be called without parentheses and . operator

Let’s take an example of various methods,

In my next post we’ll talk about Scala Classes, Objects & Singleton Objects.

nJoy Learning…..!!!!! 🙂

Leave a Reply

Notify of