Scala Partially Applied Pattern Matching Functions

I am posting this question out of curiosity to find out if anyone knows how the template works in the following case. Let's say I have a function value defined as follows:

val f = (s: String) => s.toInt 

This type, of course, is String => Int. Now I want to create a new function based on a template corresponding to the output of what is passed to this function. I can determine that as follows:

 val f2 = f(_: String) match { case i: Int => i + 2 } 

Now my new function is also from String => Int, but it adds 2 during the process. It can be called as follows:

 scala> f2("3") res0: Int = 5 

If I do the same without a partial application, I get a match based on the function itself:

 val f3 = f match { case x => "matched: " + x } 

Now the value f3 is assigned to "match <function1>"; because he called the match with "f" as the value.

So my question is, how does Scala talk about all these two? They are both function values, and both are of type String => Int. In fact, if I assign the partially applied value of the function to the temporary variable tmp before starting the match, then it will behave just like f3:

 val tmp = f(_: String) val f4 = tmp match { case x => "matched: " + x } 

Now f4 is assigned a "correspondence <function1>" instead of String => Int.

I can see the meaning in the desire to do this, I just wonder how it is done. Is this just a magical Scala that somehow finds out that you partially apply the function in the context of the correspondence so that it generates something else ...

+4
source share
1 answer

Here's how underscores work.

 f(_: String) match { case i: Int => i + 2 } 

is short for

 (x: String) => (f(x) match { case i: Int => i + 2 }) 

(brackets added to make things clearer), but your other examples are equivalent

 (x: String => f(x)) match { case y => "matched: " + y } 
+9
source

All Articles