我刚刚将以下Java转换为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++] = '/';
我的第一次尝试是一个数组:
val map1 = (
('A' to 'Z') ++ ('a' to 'z') ++ ('0' to '9')
).toArray[Char] ++ Array('+', '/');
这个有效!更多阅读,我意识到Array
是一个可变类型,而List
是不可变的,所以我把它改为:
val map1 = (
('A' to 'Z') ++ ('a' to 'z') ++ ('0' to '9')
).toList ++ List('+', '/');
这里的代码更具可读性,toList
特征没有采用类型参数,而我需要编写toArray[Char]
。为什么?这是一个Java互操作性问题,还是库不一致,toList
来自Iterable
而toArray
来自Collection
?
答案 0 :(得分:2)
您可以连接两个不同类型的列表;结果是他们最不共同的祖先列表:
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)
您应该使用('a' to 'z')
代替('a' until 'z'+1)
。
在Scala 2.8中,.toArray运行正常 - 但这可能是因为Range(to
和until
)是通用的:
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)
我怀疑在2.7.x中,范围总是给你整数。
答案 1 :(得分:0)
我无法重现你提到的问题:
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, +, /)