Fundamentals 4 min read

Understanding Methods and Functions in Scala

This article explains the distinction between methods and functions in Scala, demonstrates how to declare, define, and invoke them using val, def, and object syntax, and provides multiple code examples illustrating abstract methods, return types, Unit, and practical method calls.

Big Data Technology & Architecture
Big Data Technology & Architecture
Big Data Technology & Architecture
Understanding Methods and Functions in Scala

In Scala, a method is a member of a class, while a function is a full object that can be assigned to a variable; defining a function inside a class is effectively defining a method.

Scala uses val to define a function and def to define a method. Example:

class Test{
  def m(x: Int) = x + 3
  val f = (x: Int) => x + 3
}

Method declaration follows the format def functionName([parameter list]): [return type]. Omitting the equals sign and body makes the method abstract.

Method definition starts with the def keyword, followed by an optional parameter list, a colon, the return type, an equals sign, and the method body:

def functionName([parameter list]): [return type] = {
   function body
   return [expr]
}

The return type can be any valid Scala type. For example, a method that adds two integers:

object add{
   def addInt(a: Int, b: Int): Int = {
      var sum: Int = 0
      sum = a + b
      return sum
   }
}

If a method does not return a value, it can return Unit, which is analogous to Java's void:

object Hello{
   def printMe(): Unit = {
      println("Hello, Scala!")
   }
}

Scala provides several ways to call methods. The standard call syntax is functionName(parameter list), and when using an instance you can call instance.functionName(parameter list), similar to Java.

Example combining definition and invocation:

object Test {
   def main(args: Array[String]) {
        println("Returned Value : " + addInt(5,7))
   }
   def addInt(a: Int, b: Int): Int = {
      var sum: Int = 0
      sum = a + b
      return sum
   }
}

Running the above code produces:

$ scalac Test.scala 
$ scala Test
Returned Value : 12
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingfunctionsScalamethods
Big Data Technology & Architecture
Written by

Big Data Technology & Architecture

Wang Zhiwu, a big data expert, dedicated to sharing big data technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.