scala - PartialFunction and MatchError -
there 2 ways define pf: 1) literal case {}
syntax , 2) explicit class. need following function throw matcherror, in second case doesn't happen.
1) case
val test: partialfunction[int, string] = { case x if x > 100 => x.tostring }
2) class
val test = new partialfunction[int, string] { def isdefinedat(x: int) = x > 100 def apply(x: int) = x.tostring }
should i, in seconds case, manually call isdefinedat
, shouldn't called implicitly compiler?
you have call isdefinedat
manually in 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 want avoid code, can use first way define partial function. syntactic sugar , result in valid definition of both isdefinedat
, apply
. described in scala language specification, first definition expand 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 } }
Comments
Post a Comment