scala map parentheses and curly brackets

Original address: http://hongjiang.info/scala-pitfalls-2/

When spark programming, I saw such a usage:

As a two-and-a-half-day contact with scala, I can't understand it. After a lot of searching, I saw this answer:

The following question, on the surface, is a question of parentheses and curly braces.

// The map method cannot be compiled in this way

scala> List(2).map( case 2 => "OK" )

// replace it with curly braces

scala> List(2).map{ case 2 => "OK" }

If you don't know why, it's kind of weird. To analyze it, first of all, the map method accepts a function that maps the elements in the List to other types .

It's not actually case 2 => "OK" a lambda expression (that is, it's not a function), it's a pattern matching statement.
Then why can it compile and pass in the second line?

If you are a little bit basic, you will know that the curly braces of a method have two meanings:
1) The parentheses of a function in scala can be represented by curly braces, that is,  and  are the same thingfoo{xx}foo(xx) . (One thing here refers to the parentheses of the function)
2) For a method with only one parameter, the parentheses can be omitted and map(lambda)can be written as  map lambda, that is, this block {case 2 => "OK"} together with the curly braces as a whole is a lambda (function literal).

This is the answer to the top question.

 

 

This is obviously the second one (the reason depends on the compiler's priority in parsing, it seems that treating curly braces as part of a lambda literal is higher than treating curly braces as parentheses), then Why add curly braces {case 2 => "OK" }can be used as a function literal?

This leads to the concept of partial function. The so-called partial function (also called partial function) corresponds to the complete function. The ordinary method is a complete function, that  f(i:Int) = xxx is, all Int types are used as parameters, which is a mapping to the entire Int set; The partial function is the mapping of part of the data. {case 2=> "OK" }For example, the above only maps 2. The realization of partial function is expressed by pattern matching.

scala> val p:PartialFunction[Int,String] = { case 2 => "OK" }

Because the partial function is  { case x => y } described in this special way, the above {case 2=>"OK"}is regarded as a partial function literal, and the type behind the partial function PartialFunction[A,B]is inherited from Function1[A,B], so this anonymous partial function is passed to the map method is ok.

Summary: Expressions  {case x=>y}are treated as partial function literals.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325584247&siteId=291194637