Landon Kuhn
Landon Kuhn

Reputation: 78421

Canonical way for empty Array in Scala?

What is the canonical way to get an empty array in Scala? new Array[String](0) is too verbose.

Upvotes: 67

Views: 65344

Answers (5)

xmar
xmar

Reputation: 1809

Late to the party, but I like the expressiveness of:

Array.empty[String]

Upvotes: 0

galbarm
galbarm

Reputation: 2543

If the array type is one of the primitives, you can use the shortcuts from scala.Array.

For example for a byte array it would be:

val arr = Array.emptyByteArray

This is useful when the type cannot be inferred and you want to remain less verbose.

Upvotes: 5

Eastsun
Eastsun

Reputation: 18859

val emptyArray =  Array.empty[Type]

Upvotes: 68

soc
soc

Reputation: 28423

Array() will be enough, most of the times. It will be of type Array[Nothing].

If you use implicit conversions, you might need to actually write Array[Nothing], due to Bug #3474:

def list[T](list: List[T]) = "foobar"
implicit def array2list[T](array: Array[T]) = array.toList

This will not work:

list(Array()) => error: polymorphic expression cannot be instantiated to expected type;
    found   : [T]Array[T]
    required: List[?]
        list(Array())
                  ^

This will:

list(Array[Nothing]()) //Nothing ... any other type should work as well.

But this is only a weird corner case of implicits. It's is quite possible that this problem will disappear in the future.

Upvotes: 6

sepp2k
sepp2k

Reputation: 370112

Array[String]()

You can leave out the [String] part if it can be inferred (e.g. methodThatAlwaysTakesAStringArray( Array() )).

Upvotes: 96

Related Questions