Define an object that extends PartialFunction, implement directly using cases

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

for example

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

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

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

? This would eliminate the need to define isDefinedAt and apply and simplify the record types of certain (user-predefined lib) types.

+4
source share
1 answer

, ?

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)
}

:

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

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)
}

:

object PartialFunctionClass extends DelegatingPartialFunction[Int,Boolean] {
  val underlying = {
    case 1 => true
  }
}
+6

Source: https://habr.com/ru/post/1528183/


All Articles