I was reading about scala anonymous functions here and saw that they can take the format:
{ case p1 => b1 … case pn => bn }
However, I thought that this was how partial functions were written. In fact, in this blog post, the author calls a partial function an anonymous function. At first he says that collect takes a partial function but then appears to call it an anonymous function ("collect can handle the fact that your anonymous function...").
Is it just that some anonymous functions are partial functions? If so, are all partial functions anonymous? Or are they only anonymous if in format like Alvin Alexander's example here:
val divide2: PartialFunction[Int, Int] = {
case d: Int if d != 0 => 42 / d
}
From the documentation on pattern matching anonymous functions that you linked:
Your first code snippet is a pattern matching anonymous function, but not necessarily a partial function. It would only be turned into a
PartialFunctionif it was given to a method with aPartialFunctionparameter or assigned to a variable of typePartialFunction.So you are right that just some (pattern matching) anonymous functions are partial functions (AFAIK, function literals defined with fat arrows, such as
x => x, can only ever be used to createFunctionNinstances and notPartialFunctioninstances).However, not all partial functions are anonymous functions. A sugar-free way to define
PartialFunctions is extending thePartialFunctiontrait (which extendsFunction1) and manually overriding theisDefinedAtandapplymethods. For example,divide2could also be defined like this, with an anonymous class:You probably won't see this very often, though, as it's a lot easier to just use pattern matching to define a PartialFunction.
In the blog post by Alvin Alexander you linked, the author refers to the pattern matching anonymous partial function literal as an anonymous function only because it happens to be both a partial function and an anonymous function. You could also define the function like so:
It's no longer an anonymous function, although it's still an anonymous object that's the instance of an anonymous class. Or you could define a singleton object beforehand and then use that.
No matter how you define it, though, it's a partial function.