You will have to call isDefinedAt
manually in your apply
method:
val test = new PartialFunction[Int, String] {
def isDefinedAt(x: Int) = x > 100
def apply(x: Int) = if(isDefinedAt(x)) x.toString else throw new MatchError(x)
}
If you want to avoid this code, you can simply use the first way to define your partial function. It is syntactic sugar and will result in a valid definition of both isDefinedAt
and apply
. As described in the Scala language specification, your first definition will expand to the following:
val test = new scala.PartialFunction[Int, String] {
def apply(x: Int): String = x match {
case x if x > 100 => x.toString
}
def isDefinedAt(x: Int): Boolean = {
case case x if x > 100 => true
case _ => false
}
}