F# how to return have value a tuple or null

我的未来我决定 提交于 2019-12-23 12:39:08

问题


    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 have null as a valid value, so you cannot use null 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 of null 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!