Jeriho
Jeriho

Reputation: 7299

Creating classes that can be instantiated with single or multiple elements as constructor's argument in Scala

I want to have class that can be instantiated with 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?

Upvotes: 1

Views: 135

Answers (2)

sblundy
sblundy

Reputation: 61414

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)

Upvotes: 1

Randall Schulz
Randall Schulz

Reputation: 26486

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

Upvotes: 10

Related Questions