5

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
azyoot
  • 1,162
  • 8
  • 18
  • I know, this would disallow the definition of other members of this class, but in this special case, it would actually make things easier. Should I request this lang feature? Or is this achievable in a way I don't know? – azyoot Feb 21 '14 at 19:53

2 Answers2

6

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
  }
}
ghik
  • 10,706
  • 1
  • 37
  • 50
0

Another option that might work depending on the use-case is

type PartialFunctionAlias = PartialFunction[Int,Boolean]

Then:

val partialfuncval: PartialFunctionAlias = {
  case 1 => false
}
Caoilte
  • 2,381
  • 1
  • 21
  • 27