sarthak
sarthak

Reputation: 794

toString function in Scala

I'm new to Scala, I was reading about scala from the following source: http://docs.scala-lang.org/tutorials/tour/classes

It had the following code:

class Point(var x: Int, var y: Int) {
  def move(dx: Int, dy: Int): Unit = {
    x = x + dx
    y = y + dy
  }
  override def toString: String =
    "(" + x + ", " + y + ")"
}
object Classes {
  def main(args: Array[String]) {
    val pt = new Point(1, 2)
    println(pt)
    pt.move(10, 10)
    println(pt)
  }
}

The output is:

(1, 2)
(11, 12)

I wanted to ask how did the println(pt) function printed the result (1,2)? Should we not call pt.toString() to print the result as shown?

Upvotes: 2

Views: 21986

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37822

There's an overload of println that accepts a value of type Any (in Predef.scala):

def println(x: Any) = Console.println(x)

Deep inside, it calls x.toString() to get the string to print.

Upvotes: 4

Related Questions