创建可以使用单个或多个元素实例化的类作为Scala中的构造函数参数

时间:2010-06-01 13:14:52

标签: scala collections

我想拥有可以用list,array,seq,set,stack,queue等实例化的类。 在我看来

class A
class B(elems:A*)

应该处理这些事情。

这是我的解决方案:

class A
class B(elems:Iterable[A]){
    def this(elem:A) = this(Seq(elem))
}

你能建议任何改进吗?

2 个答案:

答案 0 :(得分:10)

使用: _*归属可以将任何Seq或Array传递给具有重复参数的方法:

scala> def m1(strs: String*): Int = { strs.foldLeft(0)(_ + _.length) }
m1: (strs: String*)Int

scala> m1("foo", "bar")
res0: Int = 6

scala> val ss1 = Array("hello", ", ", "world", ".")
ss1: Array[java.lang.String] = Array(hello, , , world, .)

scala> m1(ss1: _*)
res1: Int = 13

scala> val ss2 = List("now", "is", "the", "time")
ss2: List[java.lang.String] = List(now, is, the, time)

scala> m1(ss2: _*)
res2: Int = 12

答案 1 :(得分:1)

这可能是一个小小的改进。

class A
class B(elems:Iterable[A]){
    def this(elem:A*) = this(elem.asInstanceOf[Iterable[A]])
}

这将使这些合法

val b1 = new B(a1)
val b2 = new B(a2, a3)