2008/09/19

Scala Array and repeated parameters

I met an interesting Scala problem these days, which is about repeated parameter of a function. In Java you can specify varargs on a method,


public void a(String... args){
...
}


Inside that function, you get args as an Array of String.

In Scala, we have similar feature but called repeated parameter.

def a(args:String*)


The Scalabook (section 8.8) says you get that args as an instance of Array[String]. But Scala reference(pdf) has different explanation.
The type of such a repeated parameter inside the method is then
the sequence type scala.Seq[T ].

The Scala reference is right. Actually, the implementation gives you an instance of scala.runtime.BoxedObjectArray. You can treat it as an instance of Array[String] but you can not pass it as an instance of Array[String].

Say we have another method

def b(is:Array[String])

If you want to pass args instance you get in method a to method b, you get compile error:
error: type mismatch
found: String*
required: Array[String]

So here is my solution to this.

If you want to use args as an Array[String] with method a or pass it to Java, you need to unboxed it first.

args.asInstanceOf[BoxedObjectArray].unbox(classOf[String]).
asInstanceOf[Array[String]]

If you want to pass args to another method, like b mentioned before, in Scala as paramter of type Array[String], you only need to get an array from that Seq

args.toArray[String]

Although you get another instance of BoxedAnyObject, but when passing parameter to method b, scala compiler can auto-unbox for you.

For interesting implementation detail, see David's excellent writing about Scala array.

1 comments:

Grzegorz Kossakowski 22/7/09 02:34  

I've run into that problem as well.

Thanks for sharing your thoughts.

Footer

  © Blogger template 'Grease' by Ourblogtemplates.com 2008

Back to TOP