Re: Different behaviour from Option map in scala compared to Optional map in java

Kevin Wright <[email protected]> Sun, 17 Apr 2016 22:41:18 +0100
Newsgroups gmane.comp.lang.scala
Message-ID <CABHxxC3Z6ACPfPtQDtMPoavxR-uisKi13FDQ9XAnKb4F9LqT4Q@mail.gmail.com>
A trivial example can serve to demonstrate the problem of adding magical
behaviour around nulls.

val theMap = Map(1 -> “one”, 2 -> null)
println(theMap get 1)
println(theMap get 2)
println(theMap get 3)

Three different results… “one”, Some(null), None
There’s a difference in meaning here that Scala will preserve unless you
explicitly request otherwise

Some(null) indicates that there *is* a value present, and that value is null
(which is a valid subtype of String)
None indicates that the value was absent from the map

This sort of thing almost never occurs in idiomatic Scala code, it results
from Java intro, but it’s not entirely unknown.

If you want to drop that distinction, then calling Option(x) will return
Some(x), or None if x is null
This can also be used if you already have an Option that maybe contains null,
by calling:
   theDubiousOption flatMap {Option(_)}


On 17 April 2016 at 22:20, Simon Ochsenreither <
[email protected]> wrote:

>
> you're right it's not a bug, but I normally think that getting a Some
>> object means that it does not contain null, because null would be
>> represented with None.
>> This thinking leads to a NullPointerException when I try to use the
>> contained value in the returned Some object.
>> This is strange in my eyes because I would use the map method from Option
>> to prevent getting NullPointerExceptions.
>> Therefore I think it's more intuitive if map returns Option(f(this.get))
>> instead of Some(f(this.get)), because this would prevent a
>> NullPointerException if I use the returned Option object from map.
>>
>
> Option[T] doesn't (and can't) add additional constraints on T. If null is
> a valid value of T, Some(null) is a perfectly fine value of Option.
> Adding ad-hoc null-handling to some types would be more or less just
> trying to paper over the issue that most things in Scala/on the JVM are
> nullable. The problem should be fixed (maybe in Dotty), not the symptoms.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/d/optout.