Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define an object extending PartialFunction, implement directly with cases

I'm quite new to Scala but I already love it. I have read tutorials and articles on partial functions. What I would like to achieve is to have an object extending PartialFunction[...,...] and have it defined directly with cases, without needing to define isDefinedAt and apply methods.

For example

val partialfuncval : PartialFunction[Int,Boolean] = {
    case 1 => false
}

is a valid definition of a partial function. But why can't I write

object PartialFunctionClass extends PartialFunction[Int,Boolean] {
    case 1 => false
}

? This would cancel the need of defining isDefinedAt and apply and would make writing classes of certain (predefined by a lib I'm using) types easier.

like image 446
azyoot Avatar asked Feb 21 '14 19:02

azyoot


People also ask

How do you define a partial function in Scala?

Therefore, we can define a partial function for each requirement: val negativeOrZeroToPositive: PartialFunction[Int, Int] = { case x if x <= 0 => Math.abs(x) } val positiveToNegative: PartialFunction[Int, Int] = { case x if x > 0 => -1 * x }

Is a partial function a function?

This is the case in calculus, where, for example, the quotient of two functions is a partial function whose domain of definition cannot contain the zeros of the denominator. For this reason, in calculus, and more generally in mathematical analysis, a partial function is generally called simply a function.

When to use partial function Scala?

When a function is not able to produce a return for every single variable input data given to it then that function is termed as Partial function. It can determine an output for a subset of some practicable inputs only. It can only be applied partially to the stated inputs.


1 Answers

Would one of these options suffice you?

Option 1

abstract class DelegatingPartialFunction[-T,+R](underlying: PartialFunction[T,R]) extends PartialFunction[T,R] {
  def apply(t: T) = underlying.apply(t)
  def isDefinedAt(t: T) = underlying.isDefinedAt(t)
}

Then:

object PartialFunctionClass extends DelegatingPartialFunction[Int,Boolean]({
  case 1 => false
})

Option 2

trait DelegatingPartialFunction[-T,+R] extends PartialFunction[T,R] {
  val underlying: PartialFunction[T,R]
  def apply(t: T) = underlying.apply(t)
  def isDefinedAt(t: T) = underlying.isDefinedAt(t)
}

Then:

object PartialFunctionClass extends DelegatingPartialFunction[Int,Boolean] {
  val underlying = {
    case 1 => true
  }
}
like image 195
ghik Avatar answered Nov 15 '22 07:11

ghik