Scala this keyword

Keywords are the words in a language that are used to represent some predefined actions or some internal process. We use the this keyword when we want to introduce the current object for a class. Then using the dot operator (.), we can refer to instance variables, methods and constructors by using this keyword. this keyword is also used with auxiliary constructors.

Let’s understand this keyword with some examples.

Example #1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to illustrate this keyword
class Addition(i:Int)
{
    // using this keyword
    def this(i:Int, j:Int)
    {
        this(i)
        println(i + " + " + j + " = " + { i + j })
    }
  
// Creating object
object GFG
{
    // Main method
    def main(args:Array[String])
    {
        var add = new Addition(15, 12)
    }
      
}

chevron_right


Output:

15 + 12 = 27

In above example, a class addition defined which consist one parameter and in that classs we created a method using this keyword with two parameters i and j. In this method a primary constructor is also invoked (i.e this(i)).
 
Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to illustrate this keyword
class geeks
{
    var Lname: String = ""
    var Articles = 0
      
    // Using this keyword
    def this(Lname:String, Articles:Int )
    {
        this()
        this.Lname = Lname 
        this.Articles = Articles 
          
    }
    def show()
    {
        println("Language name " + Lname +
                " published article " + Articles )
    }
  
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
        var GeeksForGeeks = new geeks( "Scala", 105
        GeeksForGeeks.show()
    }
}

chevron_right


Output:

Language name Scala published article 105

As we can see, in above example, an auxiliary constructor defined with this keyword and a primary constructor called using this keyword. instance variables (i.e Lname, Articles)is also referred using dot(.) operator.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.