Filippo De Luca
Filippo De Luca

Reputation: 726

PartialFunction type

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.

Upvotes: 5

Views: 462

Answers (1)

kassens
kassens

Reputation: 4475

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.

Upvotes: 8

Related Questions