
- 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 - 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 Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- 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 - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - This Keyword
This chapter takes you through usage of the "this" keyword in Scala programming. The "this" keyword in Scala is used to reference the current instance of a class. The "this" keyword has various important purposes. For example, disambiguating between class fields and parameters, invoking other constructors, and passing the current instance as a parameter.
This Keyword
The "this" keyword refers to the current instance of a class. You can access members (fields and methods) of the current object within its scope. In Scala, this is used to differentiate between class fields and method parameters with the same name. It can also be used to call another constructor of the same class (this constructor). So, you can reuse of initialization logic across multiple constructors.
Syntax
This is simple syntax of this keyword used in Scala programming -
class ClassName(parameter1: Type, parameter2: Type) { def method(): Unit = { println(this.parameter1) } def this(parameter1: Type) { this(parameter1, defaultValue) // Additional initialization } }
Here, a class is defined with various parameters and methods. The use of this keyword inside the method of this class, so it will refer to the current instance. There is also this keyword in the auxiliary constructor (this(parameter1, defaultValue)). It calls the primary constructor with parameters. So, you can have various ways to initialize instances of the class.
These are various uses of the "this" keyword in Scala programming. We have explained some of the following.
1. Using this to Reference Class Fields
The "this" keyword can be used to reference class fields, especially when constructor parameters have the same names as class fields.
Example
The following example shows the use of the "this" keyword to differentiate between class fields and constructor parameters.
class Employee(name: String, age: Int) { private var empName: String = this.name private var empAge: Int = this.age def displayInfo(): Unit = { println(s"Employee Name: $empName, Age: $empAge") } } object Demo { def main(args: Array[String]): Unit = { val employee = new Employee("Alice", 30) employee.displayInfo() } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Employee Name: Alice, Age: 30
In the example, the Employee class uses the "this" keyword to refer to the class fields empName and empAge. These are initialized with the constructor parameters name and age.
2. Using this to Invoke Auxiliary Constructors
The "this" keyword is used to invoke auxiliary constructors within the same class. Auxiliary constructors provide alternative ways to create instances of a class.
Example
The following example shows how to use the "this" keyword to invoke an auxiliary constructor.
class Rectangle(val width: Int, val height: Int) { var area: Int = width * height // Auxiliary constructor def this(side: Int) = { this(side, side) } override def toString: String = s"Rectangle(width: $width, height: $height, area: $area)" } object Demo { def main(args: Array[String]): Unit = { val rectangle1 = new Rectangle(10, 20) val rectangle2 = new Rectangle(15) println(rectangle1) println(rectangle2) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Rectangle(width: 10, height: 20, area: 200) Rectangle(width: 15, height: 15, area: 225)
In the example, the Rectangle class has a primary constructor and an auxiliary constructor. The auxiliary constructor uses the "this" keyword to call the primary constructor. So, you can create a square with only one side length.
3. Passing this as a Parameter
The "this" keyword can be used to pass the current instance of a class as a parameter to other methods or constructors.
Example
The following example shows how to pass this as a parameter to another method.
class Person(val name: String) { def greet(person: Person): Unit = { println(s"Hello, ${person.name}! My name is ${this.name}.") } } object Demo { def main(args: Array[String]): Unit = { val alice = new Person("Alice") val bob = new Person("Bob") alice.greet(bob) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Hello, Bob! My name is Alice.
In the example, the Person class has a greet method that takes another Person object as a parameter. The "this" keyword is used to reference the current instance. So one person to greet another.
Scala this Keyword Summary
- The "this" keyword in Scala refers to the current instance of a class.
- It is used to access class fields and methods, invoke auxiliary constructors, and pass the current instance as a parameter.
- You can disambiguate between class fields and constructor parameters with the same names.