I have the following code:
private def hasRole(role: String): Boolean = {
var hasRole = false;
if(getUserDetails.isDefined){
// getAuthorities returns java.util.Collection<GrantedAuthority>
val authorities: util.Collection[_ <:GrantedAuthority] = getUserDetails.get.getAuthorities
// Wrap the collection is a Scala class
val authoritiesWrapper = JCollectionWrapper.apply(authorities);
for(authority <- authoritiesWrapper.iterator){
if(authority.getAuthority == role){
hasRole = true;
scala.util.control.Breaks.break
}
}
}
hasRole
}
The question is, is scala.util.control.Breaks.break the correct way toreturn when I’ve found the role? Doesn’t look right to me.
If you want to use breakable, you need to do it like so:
But if you find yourself doing that often, you’re probably not using the collections library to its full extent. Try instead
Also, in the example you gave, you could also
When to choose which? In general, you should use the control-flow options in the collections library if you can. They generally are the fastest and clearest. Wait, fastest–why is that? Both
breakandreturn(from within aforor other context that requires a closure–basically anything butifandwhileandmatch) actually throw a stackless exception which is caught; in thebreakcase it’s caught bybreakableand in thereturncase it’s caught by the method. Creating a stack trace is really slow, but even stackless exceptions are kind of slow.So using the correct collections method–
existsin this case–is the best solution.