Scala - How to declare multiple variables on one line

I thought I’d have a little fun with Scala today, and show different ways to declare multiple variables on one line. These aren’t the most useful or common things to do, but they’re interesting, and I know I learned at least one thing while looking into this.

You can define multiple fields on one line, separated by commas, as long as they are all the same type and have the same value:

scala> val x, y, z = 1
x: Int = 1
y: Int = 1
z: Int = 1

scala> val a, b, c:String = ""
a: String = ""
b: String = ""
c: String = ""

If you really want to have some fun, you can take advantage of Scala’s extractor functionality to declare fields with different types like this:

scala> var (x, y, z) = (0, 1.1, "foo")
x: Int = 0
y: Double = 1.1
z: java.lang.String = foo

As you can see from the output, that example creates three var fields of different types in one line of code.

Depending on your definition of “one line,” you can also define multiple fields on one line if they are separated by a semicolon:

scala> val h = "hello"; val a = 0
h: String = hello
a: Int = 0

While I don’t recommend these approaches for large applications, they can be convenient in small shell scripts.

Note that you can’t use the underscore wildcard character in this situation:

scala> val a, b, c:String = _
<console>:1: error: unbound placeholder parameter
       val a, b, c:String = _
                            ^

However, manually assigning the fields to a single literal value works:

scala> val a, b, c:String = "foo"
a: String = foo
b: String = foo
c: String = foo