3 ms·
Coercing Some (null) to None seems like a bug. Null is a valid value in the type and should be allowed (F# allows it too). Otherwise, a function might accident
by MichaelGG 12y ago
Coercing Some (null) to None seems like a bug. Null is a valid value in the type and should be allowed (F# allows it too).
Otherwise, a function might accidentally return None and cause a bug. For instance, a function that looks up s user and returns the name. The name might have null as a valid option. Some(null) indicates user found with no name. None indicates user not found.
- louthy 12y agoI hear what you're saying, but I felt that the reason for using Option in C# would be explicitly to deny nulls. If you are OK with accepting null, don't use Option and return null. I think that's slightly different with F# where you mostly deal with value types that definitely have values. It's rare that you need to pull null out of the bag (unless interop'ing with .NET libs). I understand why you might call it a bug, but I think I make the reasoning clear in the documentation. So I hope it's unlikely to cause confusion.
- hjnilsson 12y agoI feel like throwing a NullReferenceException would be the more appropriate way to deal with it. Either treat Some(null) as a valid value, or treat it as an error. Silently coercing it will lead to problems down the line, like with the Some(Some(null)) case mentioned.
- louthy 12y agoI'm definitely starting to lean that way. Thanks for the feedback.
- lomnakkus 12y agoThe proper way to do this is to have something like in Scala where you say Option(foo) if you want "foo" coerced to either Some(...) or None based on its nullity. It doesn't prevent you from using Some(null) if that's what you really mean. (Though I think it might be a reasonable idea to actually throw an error in such a case. However, there should be a way to construct a Some(null), perhaps with a name that suggests that it's not recommended. Perhaps something with "unsafe" or "unguarded" in the name.)
- louthy 12y ago> Perhaps something with "unsafe" or "unguarded" in the name. That seems like a reasonable approach.