How exactly does “case” work in partial functions in Scala?

I am just starting my seemingly steep learning curve with Scala and I can’t understand how the “case” works in partial functions exactly.

I looked at the definition of PartialFunction itself, and there I see a sample like the following:

val isEven: PartialFunction[Int, String] = { 
   case x if x % 2 == 0 => x+" is even" 
}

The part where I'm stuck is case x, if x% 2 - how does Scala know what is here? What is the formal definition of this "case" statement / keyword?

I think one of the reasons for my confusion is that in Lift I see things like the following (in Actor classes):

override def messageHandler = {
   case SomeKindOfUserMessageClass(id1, param1) => ....
   case AnotherKindOfUserMessageClass(id2) => ....
}

I understand what is going on here intuitively, but I cannot put together some unified definition of how to use the “case”. Even more perplexing for me is how the Scala compiler unravels all this.

+4
source share
4 answers

The thing you're asking for is called pattern matching . The pattern matching block can be used with a keyword match, or it can be used to define a function or partial function depending on the context.

. Scala m match { case A(x) => } A.unapply(m). case ( case , , unapply).

Scala - , , . 8 . 8.4 ​​ if case, .

+7

" " http://www.artima.com/pins1ed/case-classes-and-pattern-matching.html, , , , , "".

A sequence of cases (i.e., alternatives) in curly braces can be used anywhere a function literal can be used. Essentially, a case sequence is a function literal, only more general. , , , . Each case is an entry point to the function, and the parameters are specified with the pattern. The body of each entry point is the right-hand side of the case.

+5

case . .

case SomeKindOfUserMessageClass(id1, param1): , SomeKindOfUserMessageClass, , id1 param1. , .

case x if x % 2 == 0: , 2, , x , , x , 2.

+1

switch .

PHP case . ""... .

. , , ..... ... .

...

val x = List(1,2,3,4)
x match {
  case Nil => Nil
  case x => x map someFunction
}

-.

Check out the functional programming program for the course at scala at coursera.org. If you do, you will have a good head in scala.

+1
source

All Articles