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

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -