I see the following code in several places depicting the use of partial functions in Scala.
val divide: PartialFunction[Int, Int] = {
case d: Int if d != 0 => 42 / d
}
Here, divide is a variable whose type of is PartialFunction[Int,Int] which is a trait. I am confused about the RHS part. Since the type of the variable "divide" is: PartialFunction[Int,Int] , it needs to be instantiated by using a "new" keyword. I am not sure about the kind of syntax this is. Plus how isdefined() function automatically defined above ? ( isDefined() seems available; but it is there hidden).
Can someone please help.
The right-hand-side is a function literal in cases.
It's a literal, just like an
Int,Char,Stringdon't have anewkeyword before the literal.A function in cases has the syntax
The expected type must be fully known. If a
PartialFunctionis expected, it's taken as a PartialFunction. Otherwise, it's taken as aFunction1For the
PartialFunctionvariation, it'sisDefinedAtis defined by the patterns of the cases.