2010-03-03

Scala 2.8 Showcase - Arrays

In Scala 2.8, arrays have undergone a major redesign for many reasons - the necessity for compatibility with a bit cumbersome JVM array implementation, as well as other reasons, which are described in the official Scala 2.8 arrays document (PDF).

You should study this document if you seek implementation details; as I understand, Scala developers will not feel a change in array handling other than seeing better performance.

Repeated parameters


To conclude this short article with a bit of code, I will present this interesting example I found in the Programming in Scala book by Martin Odersky and others.

You probably know repeated parameters (they also exist in Java as of version 5 and are known as varargs).

def blah(args: String*) {
        args foreach println
    }

This function prints every string it gets - you can pass it 0 or more String arguments.

blah()
        blah("One", "Two")
        blah("Zero")

This all works. However, here's the surprise:

val array = Array("Three", "Four")
        blah(array) // mismatch!!!

This does not compile!

type mismatch;  found   : Array[java.lang.String]  required: String

Nasty; and I do not understand why this shouldn't work. Nevertheless, here is the solution:

blah(array: _*)

Strange, but works. Thank you for your attention.

Scala 2.8 Showcase


  1. Scala 2.8 Showcase - Collections
  2. Scala 2.8 Showcase - Arrays
  3. Scala 2.8 Showcase - Specialized Types

No comments:

Post a Comment