Search code examples
scalapartialfunction

Partial function in scala


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.


Solution

  • The right-hand-side is a function literal in cases.

    It's a literal, just like an Int, Char, String don't have a new keyword before the literal.

    A function in cases has the syntax

    {
      case ... => ...
      (optionally more cases)
    }
    

    The expected type must be fully known. If a PartialFunction is expected, it's taken as a PartialFunction. Otherwise, it's taken as a Function1

    For the PartialFunction variation, it's isDefinedAt is defined by the patterns of the cases.