Created
January 16, 2013 08:36
-
-
Save vmencik/4545568 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cz.vmencik.sandbox.nullcheck; | |
interface AuthorizedUser { | |
User getUser(); | |
} | |
interface User { | |
Group getGroup(); | |
} | |
interface Group { | |
String getName(); | |
} | |
public class NullcheckJava { | |
public String getGroupName1(AuthorizedUser authUser) { | |
if (authUser == null) { | |
return null; | |
} | |
User user = authUser.getUser(); | |
if (user == null) { | |
return null; | |
} | |
Group group = user.getGroup(); | |
if (group == null) { | |
return null; | |
} | |
return group.getName(); | |
} | |
public String getGroupName2(AuthorizedUser authUser) { | |
if (authUser != null) { | |
User user = authUser.getUser(); | |
if (user != null) { | |
Group group = user.getGroup(); | |
if (group != null) { | |
return group.getName(); | |
} | |
} | |
} | |
return null; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cz.vmencik.sandbox | |
trait AuthorizedUser { | |
def user: Option[User] | |
} | |
trait User { | |
def group: Option[Group] | |
} | |
trait Group { | |
def name: String | |
} | |
object OptionExample { | |
def getGroupName1(maybeAuthUser: Option[AuthorizedUser]): Option[String] = { | |
maybeAuthUser.flatMap(_.user.flatMap(_.group.map(_.name))) | |
} | |
def getGroupName2(maybeAuthUser: Option[AuthorizedUser]): Option[String] = { | |
maybeAuthUser.flatMap { authUser => | |
authUser.user.flatMap { user => | |
user.group.map { group => | |
group.name | |
} | |
} | |
} | |
} | |
def getGroupName3(maybeAuthUser: Option[AuthorizedUser]): Option[String] = { | |
for { | |
authUser <- maybeAuthUser | |
user <- authUser.user | |
group <- user.group | |
} yield group.name | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment