Scala: Generating a sequence/list of all ASCII printable characters

I ran into a couple of interesting things today when trying to generate random alphanumeric strings in Scala, which can be summarized with the code shown below. Skipping the details of what I was working on, here are several examples that show how to generate lists of alphanumeric/ASCII characters in Scala:

scala> val chars = ('a' to 'Z').toList
chars: List[Char] = List()

scala> val chars = ('A' to 'z').toList
chars: List[Char] = 
List(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)

scala> val chars = (' ' to 'z').toList
chars: List[Char] = 
List( , !, ", #, $, %, &, ', (, ), *, +, 
     ,, -, ., /, 0, 1, 2, 3, 4, 5, 6, 7, 
     8, 9, :, ;, <, =, >, ?, @, 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)

The reason for why this appears to work the way it does is because of the order of ASCII characters, which you can see at asciitable.com. Here’s one last example that takes you from the first printable characters (a blank space) up to the last, which is the tilde (~) character:

scala> val chars = (' ' to '~').toList
chars: List[Char] = 
List( , !, ", #, $, %, &, ', (, ), *, +, 
,, -, ., /, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
:, ;, <, =, >, ?, @, 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, {, |, }, ~)

If you ever need to easily generate a list of ASCII printable characters in Scala, I hope this is helpful.

A list of printable ASCII characters that are non-alphanumeric

While I’m in the neighborhood, here’s one way to create a list of all printable ASCII characters that are not numbers or letters:

val nonAlphaChars: List[Char] = (' ' to '/').toList ++:
    (':' to '@').toList ++:
    ('[' to '`').toList ++:
    ('{' to '~').toList

// result
nonAlphaChars: List[Char] = 
    List( , !, ", #, $, %, &, ', (, ), *, 
    +, ,, -, ., /, :, ;, <, =, >, ?, @, 
    [, \, ], ^, _, `, {, |, }, ~)

I can think of at least one other way to generate the same list of characters, but this is one possible approach.