Scala 中的 toString 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40074983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 08:45:08  来源:igfitidea点击:

toString function in Scala

scala

提问by sarthak

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

我是 Scala 的新手,我正在从以下来源阅读有关 Scala 的信息: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?

我想问一下println(pt)函数是怎么打印结果的(1,2)?我们不应该打电话pt.toString()来打印如图所示的结果吗?

回答by Tzach Zohar

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

有一个println接受类型值的重载Any(在Predef.scala 中):

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

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

在内部,它调用x.toString()获取要打印的字符串。