functional programming - How to early return in Scala -


this question has answer here:

i learning scala @ moment. 1 thing returns. i'm convinced far easier read remove invalid states before. now, scala functional language , i've read cutting computation bad functional style, i'm wondering if there trick or functional programming equivalent return.

this code write, clear, dumb example, i'm not looking special hack of special case, more general advice on how deal these.

if (request.headers.get(session_header).isempty) {   badrequest(session_not_set) } else {   ok(carthelper.getcart(session, user)) } 

now, i'm tempted is:

if (request.headers.get(session_header).isempty) {   badrequest(session_not_set)   return; }  ok(carthelper.getcart(session,user)) 

if have hint me!

in instances return keyword cannot avoided, doesn't have problem currently.

scenario 1: single condition scenario, current one. in instance can avoid using return simple if else.

def dosomething: anycontent = {   if (request.headers.get(session_header).isempty) {     badrequest(session_not_set)   } else {     ok(carthelper.getcart(session,user))   } } 

if session not being set common problem, can have guard around partial function.

def requiresession(req: request)(    pf: session => anycontent ): anycontent = {    request.headers.get(session_header)      .fold(badrequest("session not set"))(pf(_)) } 

and then:

// assuming play framework being used here def getcart: anycontent = action { implicit req =>   requiresession(req) { session => ok(carthelper.getcart(session, user) } } 

scenario 2: break loop using return, or called return performance improvement element.

one apparently valid use of return in scala seems unavoidable situation iterating collection first of something. can have abstracted away using collection.find , other helper methods pre-build in standard lib, sake of argument.

def inlist[t](l: list[t], value: t): boolean = {   (el <- l) {     // break loop first match found     // sake of efficiency.     if (el == value) return true;   }   false; } 

even in situations return avoidable, using different construct, , there's recursive version of can use replace apparently impossible return inside dan iteration.


Comments