I want to have class that can be instantiated wi开发者_JAVA技巧th list, array, seq, set, stack, queue etc. In my opinion
class A
class B(elems:A*)
should handle such stuff.
This is my solution:
class A
class B(elems:Iterable[A]){
def this(elem:A) = this(Seq(elem))
}
Can you suggest any improvements?
Any Seq or Array may be passed to a method with repeated parameters by using the : _*
ascription:
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
This might be a minor improvement.
class A
class B(elems:Iterable[A]){
def this(elem:A*) = this(elem.asInstanceOf[Iterable[A]])
}
That'll make these legal
val b1 = new B(a1)
val b2 = new B(a2, a3)
精彩评论