After reading this answer I've tried to play with this nice feature by myself and found out that it is ok when I'm do
scala> val Array(a,b,n) = "XXX,YYY,ZZZ".split(",")
a: java.lang.String = XXX
b: java.lang.String = YYY
n: java.lang.String = ZZZ
But is not ok with uppercase named variable:
scala> val Array(a,b,N) = "XXX,YYY,ZZZ".split(",")
<console>:9: error: not found: value N
val Array(a,b,N) = "XXX,YYY,ZZZ".split(",")
What is the reason of such behavior?
UPD Actually, the same thing with tuples assigment:
scala> val (a,b,N) = (1,2,3)
<console>:9: error: not found: value N
val (a,b,N) = (1,2,3)
Scala treats it as a constant against which to match the pattern. Observe:
scala> val N = 20
N: Int = 20
scala> val Array(a, b, N) = Array(11, 23, 20)
a: Int = 11
b: Int = 23
scala> val Array(a, b, N) = Array(11, 23, 21)
scala.MatchError: [I@195d471 (of class [I)
at .<init>(<console>:75)
at .<clinit>(<console>)
at .<init>(<console>:11)
at .<clinit>(<console>)
at $print(<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:704)
at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
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:25)
at java.lang.Thread.run(Thread.java:662)
The variables in which you want to extract the values must begin with a lower-case letter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With