Help understanding match/case

38 views
Skip to first unread message

Jim Newton

unread,
Aug 26, 2016, 4:58:41 AM8/26/16
to scala-user
Can someone explain to me what the vert "|"  is in the second case of this code?  

Also, I didn't realize that "x =>" was a valid notation?  Does it return Unit?


quad match {
case Fork(nw, ne, sw, se) =>
val cx = quad.centerX
val cy = quad.centerY
val sz = quad.size
drawRect(cx - sz / 2, cy - sz / 2, sz / 2, nw)
drawRect(cx - sz / 2, cy, sz / 2, sw)
drawRect(cx, cy - sz / 2, sz / 2, ne)
drawRect(cx, cy, sz / 2, se)
drawQuad(depth + 1, nw)
drawQuad(depth + 1, ne)
drawQuad(depth + 1, sw)
drawQuad(depth + 1, se)
case Empty(_, _, _) | Leaf(_, _, _, _) =>
// done
}

Oliver Ruebenacker

unread,
Aug 26, 2016, 5:37:27 AM8/26/16
to Jim Newton, scala-user

     Hello,

  The "|" means "or".

  Apparently, if nothing comes after the "=>", it is Unit, just like an empty block {}.

     Best, Oliver

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Oliver Ruebenacker
Senior Software Engineer, Diabetes Portal, Broad Institute

Lanny Ripple

unread,
Sep 3, 2016, 4:08:32 PM9/3/16
to scala-user, jimka...@gmail.com
See http://scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#pattern-alternatives

Blocks that return Unit do so by having a () placed at tail position by the compiler.  That's why you can do

    def fun(x: Int): Unit = { x + 1 }

and get a ().  (This can be seen by running `scala -Xprint:-5`)

scala> def fun(x: Int): Unit = { case x if x > 0 => x + 1; case _ => }

[[syntax trees at end of                    parser]] // <console>
package $line4 {
  object $read extends scala.AnyRef {
    // ...
        def fun(x: Int): Unit = <empty> match {
          case (x @ _) if x.$greater(0) => x.$plus(1)
          case _ => ()
        }
      }
    }
  }
}


To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages