Canonical way for empty Array in Scala?

Scala

Scala Problem Overview


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

Scala Solutions


Solution 1 - Scala

Array[String]()

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

Solution 2 - Scala

val emptyArray =  Array.empty[Type]

Solution 3 - Scala

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.

Solution 4 - Scala

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.

Solution 5 - Scala

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

Array.empty[String]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLandon KuhnView Question on Stackoverflow
Solution 1 - Scalasepp2kView Answer on Stackoverflow
Solution 2 - ScalaEastsunView Answer on Stackoverflow
Solution 3 - ScalasocView Answer on Stackoverflow
Solution 4 - ScalagalbarmView Answer on Stackoverflow
Solution 5 - ScalaxmarView Answer on Stackoverflow