
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Methods
- Scala - Functions
- Scala - Methods vs Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala - Polymorphic Functions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - NumericRange
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala Advanced Types
- Scala - Union Types
- Scala - Intersection Types
- Scala - Type Aliases
- Scala - Structural Types
- Scala - Match Expression
- Scala - Singleton Type Operator
- Scala - Abstract Types
- Scala - Dependent Types
- Scala - Abstract Type Bounds
- Scala - Higher-Kinded Types
- Scala - Opaque Type Alias
- Scala - Path-Dependent Types
- Scala - Type Lambdas
- Scala - Type Inference
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Guards
- Scala - Variables in Patterns
- Scala - Type Patterns
- Scala - The Matchable Trait
- Scala - Matching Arrays
- Scala - Matching Lists
- Scala - Matching Tuples
- Scala - Exception Handling
- Scala - Extractors
- Scala - Pattern Bindings
- Scala - Regular Expressions
- Scala - Case Classes
- Scala - Partial Functions
- Scala - Packaging and Imports
- Scala - Implicit Imports
- Scala - Export Clauses
- Scala - Nested Packages
- Scala - Chained Packages
- Scala - Package Objects
- Scala Files I/O
- Scala - Files I/O
- Scala - Writing Files
- Scala - Listing Files
- Scala - Deleting Directories
- Scala - Check File Exists
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Process Management
- Scala - Scaladoc
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala Unit Testing
- Scala - Unit Testing
- Scala - uTest
- Scala - MUnit
- Scala - ScalaTest Runner
- Scala - ScalaMock
- Scala - JUnit
- Scala - Mocking
- Scala - BDD Testing
Scala Methods vs Functions
This chapter takes you through the differences between methods and functions in Scala programming. Both methods and functions are fundamental in Scala. But these have distinct characteristics and usages.
Introduction to Methods and Functions
Both methods and functions in Scala are reusable blocks of code. These perform specific tasks. However, both of these have some differences.
Methods
Methods in Scala are defined inside classes, traits, and objects. You can define a method using the def keyword in Scala. Methods can take parameters and return values. Methods encapsulate logic to be executed when called. These are invoked using the dot notation on objects or instances.
Functions
Functions in Scala are first-class citizens. It can be assigned to variables, passed as arguments, and returned from other functions. These are defined using function literals (also known as lambda expressions) and can be treated as values. You can define a function using the def keyword and the => symbol for anonymous function.
Differences between Methods and Functions
Methods
You can define a method using the def keyword, followed by the method name, parameter list, return type, and method body.
The syntax of the method is -
def methodName(param1: Type1, param2: Type2): ReturnType = { // Method body // return some value of ReturnType }
Functions
You can define a function using the => syntax (function literal). It can be assigned to variables.
The syntax of the function is -
val functionName = (param1: Type1, param2: Type2) => { // Function body // return some value }
Example
The following examples shows the differences between methods and functions in Scala programming -
Method Example
object Demo { def add(a: Int, b: Int): Int = { a + b } def main(args: Array[String]): Unit = { val sum = add(5, 3) println(s"The sum is: $sum") } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The sum is: 8
In the example, the add method takes two parameters of type Int. This method returns their sum. The Demo object calls the add method and prints the result.
Function Example
object Demo { def main(args: Array[String]): Unit = { val add = (a: Int, b: Int) => a + b val sum = add(5, 3) println(s"The sum is: $sum") } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The sum is: 8
In the example, an anonymous function is assigned to the add variable. The Demo object calls the anonymous function and prints the result.
Invoking Methods vs. Functions
Invoking Methods
Methods are invoked on instances of classes, traits, and objects using dot notation.
Example
val calc = new Calculator() val result = calc.add(5, 3)
Invoking Functions
Functions are invoked by calling the function variable with the required parameters.
Example
val add = (x: Int, y: Int) => x + y val result = add(5, 3)
Passing Functions as Parameters
You can pass functions as parameters to other functions and methods. So, there can be higher-order functions.
Example
object Demo { def applyFunction(f: (Int, Int) => Int, a: Int, b: Int): Int = { f(a, b) } def main(args: Array[String]): Unit = { val add = (a: Int, b: Int) => a + b val sum = applyFunction(add, 5, 3) println(s"The sum is: $sum") } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The sum is: 8
In the example, the applyFunction method takes a function f as parameter with two integers a and b. The Demo object calls applyFunction with an anonymous function that adds two numbers.
Method-to-Function Conversion
You can convert a method into a function by using the underscore _ syntax.
Example
class Calculator { def add(x: Int, y: Int): Int = { x + y } } object Demo { def main(args: Array[String]): Unit = { val calc = new Calculator() val addFunction = calc.add _ val result = addFunction(5, 3) println(s"The sum is: $result") // The sum is: 8 } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The sum is: 8
Difference Between Methods and Functions
The following table shows the differences between methods and functions in Scala −
Feature | Methods | Functions |
---|---|---|
Definition | Defined using the def keyword inside classes, traits, and objects. | Defined using function literals (=> syntax) and can be assigned to variables. |
Invocation | Invoked using dot notation on instances of classes, traits, and objects. | Invoked by calling the function variable with required parameters. |
Scope | Associated with instances of classes, traits, and objects. | First-class citizens. These can exist independently and can be assigned to variables. |
Return Type | Must explicitly specify return type. | Return type inferred unless explicitly specified. |
Parameter Types | Parameter types must be explicitly declared. | Parameter types can be inferred or explicitly declared. |
Usage | Used for defining behaviors and actions within classes and objects. | Used for functional programming paradigms, higher-order functions, and more concise code. |
Conversion | Can be converted to functions using underscore (_) syntax. | N/A (Already functions by nature). |
Higher-Order Functions | Can accept functions as parameters and return function. | Are functions and can be passed around as such. |
Example |
class Calculator { def add(x: Int, y: Int): Int = x + y } |
val add = (x: Int, y: Int) => x + y |
Methods vs Functions Summary
- Methods and functions are reusable blocks of code in Scala. But these have some differences.
- Methods are defined within a class, object, and trait using the def keyword and are invoked using dot
- Functions are first-class citizens. Functions can be assigned to variables, passed as arguments, and returned from other functions. These can be defined using the def keyword and the => symbol is used for anonymous functions.