Why does Iterables.find() in Guava throw NoSuchElementException, instead of returning null? - guava

I love Google Guava and use it a lot, but there is one method I always find me writing..
public static <T> T tryFind(Iterable<T> iterable, Predicate<T> predicate){
for(T t : iterable){
if(predicate.apply(t)){
return t;
}
}
return null;
}
To me this seems to be a very useful addition to Iterables (also to Iterators for that matter), so I'm wondering why it's missing. Also, while I can see the point of having a method that throws NoSuchElementException, perhaps to distinguish between finding a null and not finding the element, that situation only comes up if the predicate you are using is
public boolean apply(T t){
return t==null;
}
which doesn't seem to be a common case.
So why did guava designers chose to have this behavior, instead of just returning null if it can't find it?
Here is the javadoc for [Iterables.find()][1]
[1]: http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html#find(java.lang.Iterable, com.google.common.base.Predicate)

We're adding another overload of find() which accepts a default value.

Likely because null is a valid return value. Generally speaking, unless there is a good reason to not support null then it should be supported. If it is supported then you have to handle the case where it exists.

Instead of tryFind() you can use filter and check if it returns an empty collection.
I found that always working with collections is cleaner than directly asking objects.

In my opinion, the NoSuchElementException is better than a late and very difficult to debug NPE...
In most cases, when you are searching an object in a "collection", you know that you would probably find it.
If the object you're looking for is not in the "collection", you're facing an exceptional case... According to me, the NoSuchElementException feedback is more explicit than the meaningless "null".
The default value which will be introduced in a future guava release would be an efficient shortcut to treat the exceptionnal case.

Find would make sense if it could not to find rather finding default value.
Optional<T> Iterables.find(Iterable<T>, Predicate<? super T>)

Related

Best way to implement behavior based in type in scala

In a friendly chat that I was having with a friend during a code review we notice that in the code there was a lot of:
unknownTypeVal match {
case asStr: String => //DO SOMETHING FOR STRING
case asInt: Integer => //DO SOMETHING FOR Integer
case asMyOwnClass: MyOwnClass => //DO SOMETHING FOR MyOwnClass
}
problem that was initially generated by methods that return Any or Option and there is no way to remove that because we are using libraries as XPath, and JSONPath, which return instances of Any or Option for a provided path.
I don't want to get into discussions of "preference", this is not an opinion question, I want to know either by standard defined preferably by Scala, or any other organization of impact, to do this kind of "type checking" in code in a more organized way, we think that this functionality can be reduced to a single function call to a method which contains a map of function and based on "something" (name of the class or something else that I do not know right now) determine how to process such parameter:
process(myAnnonimusVal: Any) = myMapOfFunct(myAnnonimusVal.getClass) //and based on the function that this will return execute such function pasing myAnnonimusVal
what is encouraged to do by Scala devs or Scala community
In principle, match is the cleanest way to execute code conditional on matching the Any type to something else. Any chain of if-else, instanceOf, etc is bound to turn out to be even more cumbersome and less elegant. A possible exception is a case where you know what the actual type is and can act accordingly, where a direct cast might be permissible.
That said, if you find yourself making the same matches many times, you might as well encapsulate the match in order to avoid code repetition. A partial function might be exactly what you have in mind here.

How do I return a None in scala?

I've been learning Scala recently and one of the things I've seen most is talk about how you shouldn't use null but instead use None. I've had to resort to using null some times because I don't understand how None works exactly.
My biggest problem is when I have methods which return an object say:
def func: SomeObjType = {
if(something)
new SomeObjType
else
null or None
If I return null, it works perfectly well but whenever I try to return None it doesn't work.
What am I doing wrong?
def func : Option[SomeObjType] = {
if (cond)
Some(new SomeObjType)
else
None
}
None, as you can see in the scaladocs here, is an extension of Option. It only checks out if your return type is expected to be an Option.
You can alter your code as Marth suggests, but in practice, Option makes for rather ugly code if it is used constantly.
If you are dealing with Lists, returning a Nil would be quite suitable.
I personally just return Nothing, just because it sounds cool, and because its autoinheritence of every class (including SomeObjType) makes it simple to deal with.
The following article is a very useful piece about these absentee-types in Scala:
A Post About Nothing, by Matt Malone
And really, with all these alternatives, there's little appeal for a lower-case null. It even pales in the face of the aesthetically-pleasing Null. Quirks aside, null and Null can be used more or less interchangeably.

Why is there an Option.get method

Why is the method get defined in Option and not in Some?
One could apply pattern matching or use foreach, map, flatMap, getOrElse which is preferred anyway without the danger of runtime exceptions if None.get is called.
Are there really cases where the get method is so much convinent that it justifies this? Using the get method reminds me to Java where "I don't have to check for null because I know the var is set" and then see a NullPointerException.
Option.get is occasionally useful when you know, by reasoning that isn't captured by the type system, that the value you have is not None. However, you should reach for it only when you've tried:
Arranging for this knowledge to be expressed by your types.
Using the Option processing methods mentioned (flatMap, getOrElse etc), and none of them fit elegantly.
It's also convenient for throwaway / interactive code (REPL, worksheets etc).
Foreword
Scala was created with compatibility for the JVM as a target.
So it's pretty natural that Exceptions and try/catch should be considered as part of the language, at least for java interoperability.
With this premise in mind, now to the point of including interfaces that can throw errors in algebraic data types (or case classes if you prefer).
To the Question
Assume we encapsulate the get method (or head for List) only in Some instance.
This implies that we're forced to pattern match on the Option every time we want to extract the value. It wouldn't look pretty neat, but it's still a possibility.
We could getOrElse everywhere but this means that I can't signal a failure through the error stack if using imperative style (which is not forbidden in scala, the last time I checked).
My point here is that getOrElse and headOption are available to enforce a functional style when desired, but get and head are good alternatives if imperative is a choice fit to the problem or the programmer's preference.
There is no good reason for it. Martin Odersky added it in this commit in 2007, so I guess we'd need to ask him his motivations. The earlier version had getOrElse semantics.
If you examine the commit provided. It's kind of obvious why and
when it is used. The get is used to unbox when you are sure there is Something in the
Option. It would also serve to be an inheritable method where None.get Throws an exception and Some.get unboxes the contents.
In some cases, when your Option turns out to be a None, there is no recourse and you want to throw an exception. So, instead of writing
myOption match {
case Some(value) => // use value
case None => throw new RuntimeException("I really needed that value")
}
you can simply write
myOption.get // might throw an exception
It also makes Option much nicer to use from Java, in conjunction with isDefined:
if (myOption.isDefined()) process(myOption.get());
else // it's a None!

Scala proper use of break to return

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:
import scala.util.control.Breaks._
breakable {
for (i <- 0 to 10000) { if (i>3) break }
}
But if you find yourself doing that often, you're probably not using the collections library to its full extent. Try instead
authoritiesWrapper.iterator.exists(_.getAuthority == role)
Also, in the example you gave, you could also
if (authority.getAuthority == role) return true
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 break and return (from within a for or other context that requires a closure--basically anything but if and while and match) actually throw a stackless exception which is caught; in the break case it's caught by breakable and in the return case 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--exists in this case--is the best solution.
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.
Since your just looking for the first instance of authority.getAuthority == role you can use find which does exactly that and is the idiomatic way to do this.
authoritiesWrapper.iterator.find(authority => authority.getAuthority == role)
or more concisely
authoritiesWrapper.iterator.find(_.getAuthority == role)
These return an Option type which you can get the value of authority from if it exists.
I can only offer you generalities, but I hope it's at least a little helpful...
Unfortunately, your sample code contains free identifiers, so it's not possible for me to understand what it does without guessing and assuming.
You're thinking about the problem wrong. What is it you're doing here? You're finding a element of a collection. Use the library! It has all manner of such things off-the-shelf.
When it comes to dealing with Option[Something] the preferred approach is to map over it. If it's a None, you get a None out. If it's Some(thing) then the function you pass to map will be applied to thing and the result will be Some(what-your-function-returned-for-thing).
Alternatively, and what newcomers to Scala often find more palatable, you can use pattern matching on an Option to effectively distinguish the None case from the Some(thing) case.
When it comes to dealing with Java libraries, it's best to push the conversions from and to the Java collections to the very periphery of your code and keep the bulk of your code idiomatic Scala using native Scala collections.
The same goes for nulls coming from Java. Turn them into Option at the earliest possible time. As a convenience, the Option(thing) factory will turn a thing that is null into a None and wrap a non-null thing in a Some
Addendum
The upshot is that you really should not be using these control flow mechanisms in this code. They're all based on exceptions (other than return) and are rather at odds with Scala's emphasis on using functional programming. The library supports a clean, succinct, efficient implementation of the essetial logic you're trying for. Don't go against the grain like this.
Why not just return true and return false replacing hasRole?
Thanks Everyone, based on #Rex Kerr answer I now have this:
private def hasRole(role: String): Boolean = {
var hasRole: Boolean = false;
if(getUserDetails.isDefined){
val authorities: util.Collection[_ <:GrantedAuthority] = getUserDetails.get.getAuthorities
val authoritiesWrapper = JCollectionWrapper.apply(authorities);
hasRole = authoritiesWrapper.iterator.exists(_.getAuthority == role)
}
hasRole
}
which seems to look and feel right. I'm using exists to see of the role exists in the collection and then returning that result. By default false is returned if the user is not defined (not logged in).
Please comment if this is still not perfect.

The Scala equivalent of PHP's isset()

How do I test and see if a variable is set in Scala. In PHP you would use isset()
I am looking for a way to see if a key is set in an array.
First, Array in Scala does not have keys. They have indices, and all indices have values in them. See the edit below about how those values might be initialized, though.
You probably mean Map, which has keys. You can check whether a key is present (and, therefore, a value) by using isDefinedAt or contains:
map isDefinedAt key
map contains key
There's no practical difference between the two. Now, you see in the edit that Scala favors the use of Option, and there's just such a method when dealing with maps. If you do this:
map get key
You'll receive an Option back, which will be None if the key (and, therefore, the value) is not present.
EDIT
This is the original answer. I've noticed now that the question is not exactly about this.
As a practical matter, all fields on the JVM are pre-initialized by the JVM itself, which zeroes it. In practice, all reference fields end up pointing to null, booleans are initialized with false and all other primitives are initialized with their version of zero.
There's no such thing in Scala as an "undefined" field -- you cannot even write such a thing. You can write var x: Type = _, but that simply results in the JVM initialization value. You can use null to stand for uninitialized where it makes sense, but idiomatic Scala code tries to avoid doing so.
The usual way of indicating the possibility that a value is not present is using Option. If you have a value, then you get Some(value). If you don't, you get None. See other Stack Overflow questions about various ways of using Option, since you don't use it like variable.isDefined in idiomatic code either (though that works).
Finally, note that idiomatic Scala code don't use var much, preferring val. That means you won't set things, but, instead, produce a new copy of the thing with that value set to something else.
PHP and Scala are so different that there is no direct equivalent. First of all Scala promotes immutable variables (final in Java world) so typically we strive for variables that are always set.
You can check for null:
var person: Person = null
//...
if(person == null) {//not set
//...
}
person = new Person()
if(person == null) {//set
//...
}
But it is a poor practice. The most idiomatic way would be to use Option:
var person: Option[Person] = None
//...
if(person.isDefined) {//not set
//...
}
person = Some(new Person())
if(person.isDefined) {//set
//...
}
Again, using isDefined isn't the most idiomatic ways. Consider map and pattern matching.