Scala Range FAQ: How can I easily create a range of characters in Scala, such as a range of alpha or alphanumeric characters?
I learned recently that you can easily create a range of characters (a Range) as shown in the following examples. Here’s how you create a basic 'a' to 'z' range:
scala> 'a' to 'z' res0: scala.collection.immutable.NumericRange.Inclusive[Char] = NumericRange(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' to 'z' creates a range of uppercase and lowercase characters, along with many of those other characters on your keyboard:
scala> 'A' to 'z' res1: scala.collection.immutable.NumericRange.Inclusive[Char] = NumericRange(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)
Sorry, without digging into it, I don’t know why some of those other characters are included in the range, and characters like >
, <
, and others are not included.
Update: This question is answered in the Comments section below. The extra characters come from the fact that the range method simply uses the ASCII table of characters which go from
a
toz
, then have the other characters shown, followed byA
toZ
. (Thanks for the good comment.)
Here’s how to create a range of characters while skipping some of the characters:
scala> 'a' to 'z' by 2 res2: scala.collection.immutable.NumericRange[Char] = NumericRange(a, c, e, g, i, k, m, o, q, s, u, w, y) scala> 'a' to 'z' by 3 res3: scala.collection.immutable.NumericRange[Char] = NumericRange(a, d, g, j, m, p, s, v, y) scala> 'a' to 'z' by 4 res4: scala.collection.immutable.NumericRange[Char] = NumericRange(a, e, i, m, q, u, y)
Very cool.
If you ever need to create a range or string of characters in Scala, I hope this tip is helpful.