This is the existing behaviour in scala:
val m = Map(1->"a", 2->"b")
m(1) // "a"
m.get(1) // Some("a")
m(3) // Exception!
m.get(3) // None
For indexed collections (anything subclassing Seq), you can achieve the
same by using the lift method.
val xs = Seq("a", "b", "c", "d")
xs(1) // "a"
xs lift 1 // Some("a")
xs(99) // Exception!
xs lift 99 // None
The reason it's named so oddly is because Seq[T] is a subclass of
PartialFunction[Int,T], where lift is a method that converts the
PartialFunction into a Function1[Int,Option[T]]
*Note: PartialFunction is a function that isn't defined for all possible
input values, a classic example being square root where the input and
output must both be real numbers. In Scala, Maps and indexed collections
can be transparently suppled as arguments anywhere that a PartialFunction
of the same signature would otherwise be expected. It comes in handy for
implementing trivial table-based logic.*
On 5 June 2012 21:28, Cédric Beust ♔ <[email protected]> wrote:
> On Tue, Jun 5, 2012 at 1:20 PM, Mark Derricutt <[email protected]> wrote:
>
>> On 6/06/12 2:57 AM, Cédric Beust ♔ wrote:
>>
>> JQuery does the same thing: selectors return arrays of matching elements,
>> but if no elements were found, you receive an empty array instead of null.
>> Anyone who thinks this is a better idea hasn't practically worked with the
>> concept.
>>
>> Failing fast (with an NPE or, in the case above, with a Javascript
>> error regarding 'undefined') saves much more time than silently proceeding
>> with an unexpected result.
>>
>> Isn't this variation the one we WANT tho - the normal case it returns an
>> array, but it returns EMPTY when nothing is found, rather than null.
>> Given the contract says "i return 0 or more found things" thats preferred
>> IMHO. getElementById() silently returning null however....
>>
>
> Absolutely, and sadly, the Java collections make this mistake in various
> places (returning null instead of empty collections).
>
> In an ideal world, the default case never crashes (empty collections) but
> the language gives me a way to crash immediately if I receive
> null/None/Nothing (without me having to explicitly test for it).
>
> > If we had Option<>'s here I'd say "get" methods throw exceptions when
> failing,
> > "find" variations return an Option<?> of whatever.
>
> Yes, this would make Option much more useful in my opinion.
>
>
--
You received this message because you are subscribed to the Google Groups "Java
Posse" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/javaposse?hl=en.