简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM