Reece Reece - 1 month ago 10
Scala Question

How do I create a set of characters in Scala?

I'd like to create a Set of character ranges in Scala, something like A..Za..z0..9. Here's my take:

scala> ('A' to 'Z').toSet.union(('a' to 'z').toSet).union(('0' to '9').toSet)
res3: scala.collection.immutable.Set[Char] = Set(E, e, X, s, x, 8, 4, n, 9, N, j, y, T, Y, t, J, u, U, f, F, A, a, 5, m, M, I, i, v, G, 6, 1, V, q, Q, L, b, g, B, l, P, p, 0, 2, C, H, c, W, h, 7, r, K, w, R, 3, k, O, D, Z, o, z, S, d)


This can't be the idiomatic way to do this. What's a better way?

Answer

How about this:

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

Or, alternatively:

scala> (('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')).toSet
res0: scala.collection.immutable.Set[Char] = Set(E, e, X, s, x, 8, 4, n, 9, N, j, y, T, Y, t, J, u, U, f, F, A, a, 5, m, M, I, i, v, G, 6, 1, V, q, Q, L, b, g, B, l, P, p, 0, 2, C, H, c, W, h, 7, r, K, w, R, 3, k, O, D, Z, o, z, S, d)
Comments