覆盖 Scala 集中的 toString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15307213/
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
Override toString in a Scala set
提问by W.P. McNeill
I want to create a set of integers called IntSet. IntSetis identical to Set[Int]in every way except that its toStringfunction prints the elements as comma-delimited (the same as if you called mkString(",")), and it has a constructor that takes a Traversableof integers. What is the simplest way to do this?
我想创建一组名为IntSet. IntSet等同于Set[Int]以各种方式不同之处在于它的toString功能打印元素为以逗号分隔(好像你叫一样mkString(",")),它有一个构造函数一个Traversable整数。什么是最简单的方法来做到这一点?
> IntSet((1 to 3)).toString
1,2,3
I'd think there would be some one-line way to do this, but I've been fiddling around with implicit functions and extending HashSetand I can't figure it out.
我认为会有一些单行方式来做到这一点,但我一直在摆弄隐式函数和扩展HashSet,但我无法弄清楚。
The trick is to use a proxy object. Eastsunhas the answer below. Here's a slightly different version that defines a named IntSettype and makes it immutable.
诀窍是使用代理对象。Eastsun在下面给出了答案。这是一个稍微不同的版本,它定义了一个命名IntSet类型并使其不可变。
import collection.immutable.{HashSet, SetProxy}
class IntSet(values: Traversable[Int]) extends SetProxy[Int] {
override val self: Set[Int] = HashSet(values.toSeq:_*)
override def toString() = mkString(",")
}
回答by Eastsun
scala> import scala.collection.mutable
import scala.collection.mutable
scala> def IntSet(c: Traversable[Int]): mutable.Set[Int] = new mutable.SetProxy[Int] {
| override val self: mutable.Set[Int] = mutable.HashSet(c.toSeq :_*)
| override def toString = mkString(",")
| }
IntSet: (c: Traversable[Int])scala.collection.mutable.Set[Int]
scala> IntSet(1 to 3)
res0: scala.collection.mutable.Set[Int] = 1,2,3

