Scala: How to create a list of alpha or alphanumeric characters

While looking for code on how to create a random string in Scala, I came across this article, which shows one approach for creating a random string. For my brain today, it also shows a nice way to create a list of alpha or alphanumeric characters.

For instance, to create a list of alphanumeric characters, use this approach:

val chars = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')

To create a list of only alpha characters, just trim that code down to this:

val chars = ('a' to 'z') ++ ('A' to 'Z')

In the Scala REPL, you can see that this creates a Vector, which is a read-only, indexed sequence:

scala> val chars = ('a' to 'z') ++ ('A' to 'Z')
chars: scala.collection.immutable.IndexedSeq[Char] = Vector(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z)

Using the ++ operator (a method, actually) on Scala collections is a common way to merge/join/concatenate collections, and when I saw this code, I thought of what a great example it is of the ++ method.

It also shows that you can create a range of characters in Scala, which is something I didn't know you could do until recently. That's one of the things I love about Scala, it's a deep language, and I keep learning something new about it every day.

this post is sponsored by my books:

#1 New Release

FP Best Seller

Released in Sep., 2022