coding style - Scala - Pattern matching result of a for comprehension -
i'm performing pattern match on result of for-comprehension follows
val validxsrf = for( cookie <- request.cookies.get("xsrf-token"); header <- request.headers.get("x-xsrf-token"); if cookie.value == header ) yield true; validxsrf match { case some(true) => callbackfunc(); case none => throw new xsrfexception(); }
however feels little overly verbose - there cleaner way of expression this?
ideally i'd love like
for(....) match { .... }
however not appear possible in scala without wrapping entire for-comprehension in brackets.
is there cleaner / more elegant way of expressing logic?
you abbreviate things bit (assuming callbackfunc
returns string
):
def validxsrf():string = { val xsrf = for{ cookie <- request.cookies.get("xsrf-token") header <- request.headers.get("x-xsrf-token") if cookie.value == header } yield callbackfunc() xsrf.getorelse(throw new xsrfexception()) }
now if didn't want throw exception on failure case, redefine validxsrf
method around returning try
instead, this:
def validxsrf():try[string] = { val xsrf = for{ cookie <- request.cookies.get("xsrf-token") header <- request.headers.get("x-xsrf-token") if cookie.value == header } yield callbackfunc() xsrf.fold[try[string]](failure(new xsrfexception()))(success(_)) }
Comments
Post a Comment