1. Introduction

In this article, we’ll explore different ways to create an empty array in Scala. As with most programming languages, Scala provides us with a couple of different ways to create an empty array and we generally pick the one that is most suitable for our use case.

2. Creating an Empty Array

2.1. Most Canonical

The most canonical way to create an empty array in Scala is to use:

val emptyArray = Array[String]()

This will assign an empty string array to the emptyArray variable. If the type of the array can be inferred it can be omitted:

def processStringArray(array: Array[String]): Unit = {
  array +: "First String Element"
}

processStringArray(Array())

We’ve used Array() without specifying type String since it can be inferred from the method definition.

2.2. Most Explicit

If we want our code to be more explicit and less ambiguous we can use:

val emptyArray = Array.empty[Type]

Array.empty is a more readable way to create an empty array and is very clear about its intent. Similarly to the above example, we can omit the type if it can be inferred.

2.3. Primitive Shortcut

If the type of our array is one of the primitives, we can use a shortcut from the scala.Array class:

val emptyArray = Array.emptyByteArray

If the type cannot be inferred this is a good option to use over Array.empty.

Here are all the primitive Array definitions:

val emptyBooleanArray = new Array[Boolean](0)
val emptyByteArray    = new Array[Byte](0)
val emptyCharArray    = new Array[Char](0)
val emptyDoubleArray  = new Array[Double](0)
val emptyFloatArray   = new Array[Float](0)
val emptyIntArray     = new Array[Int](0)
val emptyLongArray    = new Array[Long](0)
val emptyShortArray   = new Array[Short](0)
val emptyObjectArray  = new Array[Object](0)

3. Conclusion

We’ve explored the most common ways to create an empty array in Scala.  The one we’ll choose usually depends on how verbose and ambiguous we want our code to be. On a collaborative project it’s often useful for other contributors to immediately understand what the intent of the code is, therefore, Array.empty is often the preferred approach.


« 上一篇: Scala 数组初始化