Skip to content
Related Articles

Related Articles

Improve Article

Overriding toString() method in Scala

  • Last Updated : 24 Jun, 2019

Consider the following Scala program:




// Scala Program without override toString method
  
// Creating Class
class Language(LangArticle: Int, LangName: String) 
{
  
    // Defining getLangArticle method
    def getLangArticle() : Int = {
          
        return LangArticle;
    }
      
    // Defining getLangName method
    def getLangName() : String = {
          
        return LangName;
    }
  
}
  
// Creating object
object GFG 
{
    // Main method
    def main(args: Array[String])
    {
          
        var language = new Language(50, "Scala");
          
        println(language)
          
    }
}
Output:
Language@506e1b77

The output is, class name, then ‘at’ sign, and at the end hashCode of object. All classes in Scala inherit from the Object class, directly or indirectly . The object class has some basic methods like clone(), toString(), equals(), .. etc. The default toString() method in Object prints “class name @ hash code”. We can override toString() method in our class to print proper output. Below is the example to override toString method.




// Scala Program to override toString method
  
// Creating Class
class Language(LangArticle: Int, LangName: String) 
{
  
    // Defining getLangArticle method
    def getLangArticle() : Int = {
          
        return LangArticle;
    }
      
    // Defining getLangName method
    def getLangName() : String = {
          
        return LangName;
    }
      
    // Overriding tostring method
    override def toString() : String = {
          
        return "[Total Article : " + LangArticle + 
                ", Language Name = " + LangName+"]";
    }
  
}
  
// Creating object
object GFG 
{
    // Main method
    def main(args: Array[String])
    {
          
        var language = new Language(50, "Scala");
          
        println(language)
          
    }
}
Output:
[Total Article : 50, Language Name = Scala]

In above example Language class, which is overriding the toString() method and returning string value. This method has attributes names and values. The class defines two variables LangArticle and LangName and three methods: getLangArticle, getLangName and toString. getLangArticle takes one integer arguments and return a value. getLangName takes one string arguments and return a value. toString, on the other hand, does take any parameters but returns a String value. Since toString overrides the pre-defined toString method, it has to be tagged with the override flag.

Note: When we override the any super class method . We should use override keyword before the method (i.e: override def toString()).




My Personal Notes arrow_drop_up
Recommended Articles
Page :