Reputation: 87
I am an absolute Scala novice. This question is therefore very simplistic, and hopefully someone will understand what is being asked.
When experimenting, I have seen I can create a PartialFunction instance with the following code:
val p : PartialFunction[Int, String] = {case x if x > 2 => s"x is ${x.toString}"}
My question: How is a concrete PartialFunction[Int, String] created from the function {case x if x > 2 => s"x is ${x.toString}"}
?
In particular, how does this function provide both the..
isDefinedAt(x: Int): Boolean
method definition ..and the..
apply(v1: Int): String
method definition ..that a concrete PartialFunction[Int, String] must have?
Behind the scenes, is {case x if x > 2 => s"x is ${x.toString}"}
being turned into?:
val p : PartialFunction[Int, String] = new PartialFunction[Int, String] {
override def apply(v1: Int): String = {
v1 match {
case x if x > 2 => s"x is ${x.toString}"
}
}
override def isDefinedAt(x: Int): Boolean = {
x match {
case x if x > 2 => true
case _ => false
}
}
}
Upvotes: 2
Views: 92
Reputation: 3970
The authoritative answer can be found in the Scala language specification:
8.5 Pattern Matching Anonymous Functions
An anonymous function can be defined by a sequence of cases
{ case p1 => b1 … case pn => bn }
which appear as an expression without a prior match. The expected type of such an expression must in part be defined. It must be either
scala.Functionk[S1,…,Sk, R]
for some k > 0, orscala.PartialFunction[S1, R]
, where the argument type(s)S1,…,Sk
must be fully determined, but the result typeR
may be undetermined....
If the expected type is
scala.PartialFunction[S, R]
, the expression is taken to be equivalent to the following instance creation expression:new scala.PartialFunction[S, T] { def apply(x: S): T = x match { case p1 => b1 … case pn => bn } def isDefinedAt(x: S): Boolean = { case p1 => true … case pn => true case _ => false } }
Here,
x
is a fresh name andT
is the weak least upper bound of the types of allbi
. The final default case in theisDefinedAt
method is omitted if one of the patternsp1,…,pn
is already a variable or wildcard pattern.
Upvotes: 2