简体   繁体   中英

scala Either & Neither handling

Not sure what to call this, Option would fit just as well as Either, I need to handle a 3rd case regardless.

Scalaz likely already provides something like this, but am curious to know how, without a separate library, one can concisely handle the following simple case:

I need to check if user session exists, both actual user and admin logged-in-as-user scenarios, the latter taking precedence over the former; if neither condition exists, show login screen.

The actual user session check looks like:

request.session.get(Security.username) map { id=>
  f(Success(id.toInt, request)) 
} getOrElse( onFail(request) ) // onFail = show login

and I need to add in the admin impersonating user case:

request.session.get(Security.impersonate) map { id=>
  f(Success(id.toInt, request)) 
} getOrElse( onFail(request) )

I could getOrElse it all together but would prefer to clean things up a bit, the operation is the same regardless of user or admin-as-user cases.

Not getOrElse, just orElse

scala> val userName : Option[String] = None
userName: Option[String] = None

scala> val impersonate = Some("Fred")
impersonate: Some[java.lang.String] = Some(Fred)

scala> userName orElse impersonate
res0: Option[String] = Some(Fred)

scala> val userName = Some("George")
userName: Some[java.lang.String] = Some(George)

scala> userName orElse impersonate
res1: Option[java.lang.String] = Some(George)

So in your case

request.session.get(Security.username) orElse request.session.get(Security.impersonate) map { id=>
  f(Success(id.toInt, request)) 
} getOrElse( onFail(request) ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM