下面是解释器命令的副本:
scala>val myTable = Array(Array(1))
res30: Array[Array[Int]] = Array(Array(1))
scala> myTable.map(_.map(_.toString))
res31: Array[Array[java.lang.String]] = Array(Array(1))
scala> var result = 0
result: Int = 0
scala> myTable.head
res32: Array[Int] = Array(1)
//note how applying this works
scala> res32.map(elem => if(3> result) result = 3)
res34: Array[Unit] = Array(())
scala> result
res35: Int = 3
//this also works
scala> myTable.map(_.map(_.toString))
res31: Array[Array[java.lang.String]] = Array(Array(1))
//when you combine the double map application and the anonymous function from earlier:
scala> myTable.map(_.map(elem => if(3 > result) result = 3))
java.lang.IllegalArgumentException
at java.lang.reflect.Array.newArray(Native Method)
at java.lang.reflect.Array.newInstance(Array.java:52)
at scala.reflect.ClassManifest$class.arrayClass(ClassManifest.scala:107)
at scala.reflect.Manifest$$anon$9.arrayClass(Manifest.scala:152)
at scala.reflect.Manifest$class.arrayManifest(Manifest.scala:46)
at scala.reflect.Manifest$$anon$9.arrayManifest(Manifest.scala:152)
at scala.reflect.Manifest$$anon$9.arrayManifest(Manifest.scala:152)
at scala.reflect.ClassManifest$.arrayType(ClassManifest.scala:205)
at .<init>(<console>:45)
at .<clinit>(<console>)
at .<init>(<console>:11)
at .<clinit>(<console>)
at $export(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:592)
at scala.tools.nsc.interpreter.IMain$Request$$anonfun$10.apply(IMain.scala:828)
at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
at scala.tools.nsc.io.package$$anon$2.run(package.scala:31)
at java.lang.Thread.run(Thread.java:662)
这是预期的行为吗?
首先,您应该使用foreach,而不是map,但是您已经知道了:-)
你正在尝试创建一个数组的数组的单位,它被转换为Void。在java中键入。这会导致IllegalArgumentException。
当调用map
时,Scala使用java.lang.reflect.Array.newInstance
动态创建数组。此方法不接受大小为0的值。因为,你的lambda返回一个类型为Array[Unit]
的空数组,其大小为零,当调用外部映射时,你会得到异常。
顺便说一下,在这个例子中,您真的应该使用foreach
,因为您没有尝试将数组映射到另一个数组,而是使用副作用:
scala> myTable.foreach(_.foreach(elem => if(3 > result) result = 3))
scala> result
res21: Int = 3
编辑:我误解了这个问题(参见MatthieuF答案)。问题不在于数组的大小,而在于数组的类型。只需:
就可以重现这个问题scala> java.lang.reflect.Array.newInstance(classOf[Unit], 1)
java.lang.IllegalArgumentException
at java.lang.reflect.Array.newArray(Native Method)
at java.lang.reflect.Array.newInstance(Array.java:52)
at .<init>(<console>:8)
...