tags:

views:

249

answers:

2

I just converted the following Java into Scala:

char[] map = new char[64];
int i=0;
for (char c='A'; c<='Z'; c++) map[i++] = c;
for (char c='a'; c<='z'; c++) map[i++] = c;
for (char c='0'; c<='9'; c++) map[i++] = c;
map[i++] = '+';
map[i++] = '/';

My first attempt was an array:

val map1 = (
  ('A' to 'Z') ++ ('a' to 'z') ++ ('0' to '9')
).toArray[Char] ++ Array('+', '/');

This works! A bit more reading and I realised that Array is a mutable type, while List is immutable, so I changed it to:

val map1 = (
  ('A' to 'Z') ++ ('a' to 'z') ++ ('0' to '9')
).toList ++ List('+', '/');

The code gets a little more readable here, with the toList trait not taking a type argument, whereas I needed to write toArray[Char]. Why? Is this a question of Java interoperability, or is it a library inconsistency, with toList coming from Iterable and toArray coming from Collection?

+2  A: 

You can concatenate two lists of different types; the result is a list of their least common ancestor:

scala> val l1=List(1)
l1: List[Int] = List(1)

scala> val la=List('a')
la: List[Char] = List(a)

scala> l1++la
res4: List[AnyVal] = List(1, a)

You should use ('a' to 'z') instead of ('a' until 'z'+1).

In Scala 2.8, .toArray works fine - but this is probably because Range (to and until) is generic:

scala> 'a' to 'z'
res3: scala.collection.generic.VectorView[Char,Vector[Char]] = RichChar(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)

I suspect that in 2.7.x, range always gives you ints.

wrang-wrang
So this is a "fixed in 2.8" issue. Thanks!
David Crawshaw
A: 

I cannot reproduce the problem you mentioned:

Welcome to Scala version 2.7.4.final (Java HotSpot(TM) Client VM, Java 1.6.0_16).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val map1 = ( ('A' to 'Z') ++ ('a' to 'z') ++ ('0' to '9') ).toArray ++ Array('+', '/')
map1: Array[Char] = Array(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, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, /)

scala> val map1 = (
     |   ('A' to 'Z') ++ ('a' to 'z') ++ ('0' to '9')
     | ).toArray ++ Array('+', '/');
map1: Array[Char] = Array(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, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, /)
Daniel