Efficiently and elegantly converting from Seq to IndexedSeq?

854 views
Skip to first unread message

Kenneth McDonald

unread,
Feb 2, 2011, 1:06:30 AM2/2/11
to scala...@googlegroups.com
I have a definition (using scala.collection.immutable.{Seq, IndexedSeq}:

def Absolute(root: String, components: Seq[String]) = new AbsoluteFilePath(root, IndexedSeq(components:_*))

My understanding is that internally, `components` will be expanded and passed to `IndexedSeq.apply` as an `Array[String]`. But what if components is already of type `IndexedSeq[String]`? Is there a concise way of simply passing on components without the unwrapping/IndexedSeq creation steps? I can think of one or two ways, but nothing that is as "nice" as the above...

Thanks,
Ken

Paul Phillips

unread,
Feb 2, 2011, 1:32:28 AM2/2/11
to Kenneth McDonald, scala...@googlegroups.com
On 2/1/11 10:06 PM, Kenneth McDonald wrote:
> I have a definition (using scala.collection.immutable.{Seq,
> IndexedSeq}:
>
> def Absolute(root: String, components: Seq[String]) = new
> AbsoluteFilePath(root, IndexedSeq(components:_*))
>
> My understanding is that internally, `components` will be expanded
> and passed to `IndexedSeq.apply` as an `Array[String]`.

No.

> But what if
> components is already of type `IndexedSeq[String]`?

Then you are in good shape. Java uses Array to represent varargs.
Scala uses Seq.

Vlad Patryshev

unread,
Feb 2, 2011, 11:36:06 AM2/2/11
to Kenneth McDonald, scala...@googlegroups.com
If there is no implicit method converting a Seq to IndexedSeq, it won't happen. You can try and define such a method.

2011/2/1 Kenneth McDonald <kenneth.m...@sbcglobal.net>



--
Thanks,
-Vlad

Germán Ferrari

unread,
Feb 2, 2011, 1:35:28 PM2/2/11
to Kenneth McDonald, scala...@googlegroups.com
Hi

If components is a IndexedSeq, I woul expect that components.toIndexedSeq return the same instance. This is true at least for the default IndexedSeq, Vector.


Welcome to Scala version 2.9.0.r23573-b20101124020133 (Java HotSpot(TM) Client VM, Java 1.6.0_13).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import collection.immutable.Seq
import collection.immutable.Seq

scala> import collection.immutable.IndexedSeq
import collection.immutable.IndexedSeq

scala> val s: Seq[Int] = IndexedSeq(1,2,3)
s: scala.collection.immutable.Seq[Int] = Vector(1, 2, 3)

scala> val is = s.toIndexedSeq
is: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)

scala> s eq is
res0: Boolean = true


Regards,
Germán
Reply all
Reply to author
Forward
0 new messages