Is there conditional access operator in F# (similar to new ?. in C#)?

后端 未结 3 1427
傲寒
傲寒 2021-01-18 17:14

Now that the C# 6 is finally going to have this long-anticipated ?. operator, is there similar thing in F#? And I\'m not talking about ? operator.

3条回答
  •  星月不相逢
    2021-01-18 17:38

    Idiomatic F# doesn't have null values at all, so what use would it be? In F#, the most common way to model the absence of a value is to use option.

    When I need to interoperate with .NET code that may return null, I convert it to an option as soon as possible, using a function like this:

    let toOption (x : obj) =
        match x with
        | null -> None
        | _ -> Some x
    

    As soon as you have your value modelled as an option, you can compose it with e.g. Option.map, and that serves the same purpose (but better, and safer) than the proposed C# operator.

提交回复
热议问题