Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PartialFunction type

Tags:

scala

in scala play framework I seen this code:

abstract class AnalyserInfo
case class ColumnC(typeName:String,fieldName:String) extends AnalyserInfo
case class TableC(typeName:String) extends AnalyserInfo

    val asIs :PartialFunction[AnalyserInfo,String] = {
      case ColumnC(_,f) => f;
      case TableC(typeName) => typeName
    }

What is the difference with:

val asIs: (AnaliserInfo)=>String = (info) => info match {
  case ColumnC(_,f) => f;
  case TableC(typeName) => typeName
}

There is a preferred style? and why in the first case the match keyword can be omitted?

Thank you for the support.

like image 230
Filippo De Luca Avatar asked Apr 30 '11 10:04

Filippo De Luca


People also ask

What is Partialfunction Scala?

A partial function is a function that does not provide an answer for every possible input value it can be given. It provides an answer only for a subset of possible data, and defines the data it can handle. In Scala, a partial function can also be queried to determine if it can handle a particular value.

What is partial function example?

(definition) Definition: A function which is not defined for some inputs of the right type, that is, for some of a domain. For instance, division is a partial function since division by 0 is undefined (on the Reals).

What is the difference between function and partial function?

A function is a relation such that for every a in A there exists a unique pair (a, b) in the relation. A partial function is a relation in which for every a in A there is at most one pair (a, b) in the relation.


1 Answers

Double => Double is just a shorthand for Function[Double, Double]. PartialFunction inherits from Function but adds a few methods. Most importantly, it adds the method isDefinedAt which allows you to query if the function is defined for some parameter.

The cases without a match are a special syntax to define partial functions, which generates an isDefinedAt that returns true for all matching cases.

Say we have a function that returns 1/x, but only for positive values of x, we could it define as:

scala> val f: (Double => Double) = { case x if x > 0 => 1/x }             
f: (Double) => Double = <function1>

or as:

scala> val g: PartialFunction[Double, Double] = { case x if x > 0 => 1/x }
g: PartialFunction[Double,Double] = <function1>

The second version has the benefit that we could check if the function is applicable to some parameter:

scala> g.isDefinedAt(-3)
res0: Boolean = false

This feature is for example used in Scala to implement the actor library where an Actor might only consume certain types of messages.

like image 166
kassens Avatar answered Oct 27 '22 02:10

kassens