Consider the following Scala program:
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.
[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()).
- Method Overriding in Scala
- Scala Map toString() method with example
- Scala Iterator toString() method with example
- Scala | Field Overriding
- Scala Map get() method with example
- Scala Map last() method with example
- Scala Map max() method with example
- Scala Map min() method with example
- Scala Map take() method with example
- Scala | map() method
- Scala map contains() method with example
- Scala Map tail() method with example
- Scala Map filter() method with example
- Scala Map find() method with example
- Scala Iterator take() method with example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.