Multiple assignment via pattern matching with Array is not working with uppercase vals

后端 未结 1 1898
半阙折子戏
半阙折子戏 2021-01-18 07:53

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,YY         


        
相关标签:
1条回答
  • 2021-01-18 08:31

    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.

    0 讨论(0)
提交回复
热议问题