覆盖 Scala 集中的 toString [英] Override toString in a Scala set
问题描述
我想创建一组名为 IntSet
的整数.IntSet
在各方面都与 Set[Int]
相同,只是它的 toString
函数将元素打印为逗号分隔(就像你称为 mkString(",")
),它有一个构造函数,它接受一个 Traversable
整数.最简单的方法是什么?
<代码>>IntSet((1 到 3)).toString1,2,3
我认为会有一些单行方式来做到这一点,但我一直在摆弄隐式函数并扩展 HashSet
并且我无法弄清楚.><小时>
诀窍是使用代理对象.Eastsun 在下面给出了答案.这是一个稍微不同的版本,它定义了一个命名的 IntSet
类型并使其不可变.
import collection.immutable.{HashSet, SetProxy}class IntSet(values: Traversable[Int]) extends SetProxy[Int] {覆盖 val self: Set[Int] = HashSet(values.toSeq:_*)覆盖 def toString() = mkString(",")}
scala>导入 scala.collection.mutable导入 scala.collection.mutable标度>def IntSet(c: Traversable[Int]): mutable.Set[Int] = new mutable.SetProxy[Int] {|覆盖 val self: mutable.Set[Int] = mutable.HashSet(c.toSeq :_*)|覆盖 def toString = mkString(",")|}IntSet: (c: Traversable[Int])scala.collection.mutable.Set[Int]标度>IntSet(1 到 3)res0:scala.collection.mutable.Set[Int] = 1,2,3
I want to create a set of integers called IntSet
. IntSet
is identical to Set[Int]
in every way except that its toString
function prints the elements as comma-delimited (the same as if you called mkString(",")
), and it has a constructor that takes a Traversable
of integers. What is the simplest way to do this?
> 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 HashSet
and I can't figure it out.
The trick is to use a proxy object. Eastsun has the answer below. Here's a slightly different version that defines a named IntSet
type and makes it immutable.
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(",")
}
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
这篇关于覆盖 Scala 集中的 toString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!