Scala toString 函数
Scala toString function
我有一个 class,它有一个打印字符串的方法。我想覆盖 toString 函数,以便字符串像 t|h|i|s 一样打印。我该怎么做?
我将把你的问题解释为 "has a method that returns a string" 而不是 "has a method that prints out a string," 因为我只是 猜测 这就是你的意思,你的问题问起来会是一个更难的问题。
这是一个 class Foo
,它有一个方法 bar
returns 一个字符串。 class Foo
覆盖了 toString
方法,因此它 returns bar
的值与 |
字符穿插在一起。
scala> class Foo(val bar: String) {
| override def toString: String = bar.mkString("|")
| }
defined class Foo
scala> val x = new Foo("this")
x: Foo = t|h|i|s
scala> x.bar
res0: String = this
我有一个 class,它有一个打印字符串的方法。我想覆盖 toString 函数,以便字符串像 t|h|i|s 一样打印。我该怎么做?
我将把你的问题解释为 "has a method that returns a string" 而不是 "has a method that prints out a string," 因为我只是 猜测 这就是你的意思,你的问题问起来会是一个更难的问题。
这是一个 class Foo
,它有一个方法 bar
returns 一个字符串。 class Foo
覆盖了 toString
方法,因此它 returns bar
的值与 |
字符穿插在一起。
scala> class Foo(val bar: String) {
| override def toString: String = bar.mkString("|")
| }
defined class Foo
scala> val x = new Foo("this")
x: Foo = t|h|i|s
scala> x.bar
res0: String = this