Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the toString method of Scala Rational object

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how to use the toString method of the Scala Rational object. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

In the previous example, after the Rational instance is created, the interpreter prints out "Rational@a0b0f5". The interpreter gets this interesting-looking string by calling the toString method of the Rational object. By default, the Rational class inherits the toString implementation defined on the java.lang.Object class, just printing the class name, an @ symbol, and a hexadecimal number. The main result of toString is to try to help programmers by providing statement printing, log messages, test error reports and interpreters, and debugger output information that can be used for debugging. The results provided by toString currently won't be particularly useful because it doesn't give any clues as to the number of Rational it was called. A more useful toString implementation would print out the numerator and denominator of Rational. You can overload it by adding the toString method to the Rational class: the default implementation of override, such as:

Class Rational (n: Int, d: Int) {override def toString = n + "/" + d}

The override modifier before the method definition indicates that the previous method definition is overloaded; Chapter 10 explains further. Now the scores are displayed beautifully, so we removed the println debug statement from the previous version of the Rational class. You can test Rational's new behavior in the interpreter:

Scala > val x = new Rational (1,3) x: Rational = 1pm 3 scala > val y = new Rational (5,7) y: Rational = 5pm 7 Thank you for reading! This is the end of this article on "how to use the toString method of Scala Rational object". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report