问题
let retVal =
if reader.Read() then
(reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2))
else
null
F# don't allow null to returned
How can i have value return as a tuple or a null?
回答1:
It is not that F# does not allow you to return null.
It is because then part and else part have different types.
You can use Option type.
let retVal =
if reader.Read() then
Some (reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2))
else
None
when you use retVal
, you use pattern matching:
match retVal with
| Some v -> ...
| None -> // null case
回答2:
To add some additional information to the Yin Zhu's answer, the situation with null
value in the F# language is following:
F# types such as tuples (e.g.
int * int
), which is exactly your case don't havenull
as a valid value, so you cannot usenull
in this case (other such types are function values e.g.int -> int
, lists and most of the F# library types)Types from the .NET framework can have
null
value, so you can for example write:let (rnd:Random) = null
This isn't idiomatic F# style, but it is allowed.
If you define your own F# type, it won't automatically allow you to use
null
as a valid value of the type (which follows the goal to minimize the use ofnull
in F#). However, you can explicitly allow this:[<AllowNullLiteral>] type MyType = ...
来源:https://stackoverflow.com/questions/2983242/f-how-to-return-have-value-a-tuple-or-null