F# Option equivalent of C#'s ?? operator

前端 未结 2 1723
梦谈多话
梦谈多话 2021-01-07 19:38

I am looking for a way to get the value of an F# option or use a default value if it is None. This seems so common I can\'t believe something predefined doesn\'t exist. Here

2条回答
  •  终归单人心
    2021-01-07 20:40

    You're looking for defaultArg [MSDN] ('T option -> 'T -> 'T).

    It's often used to provide a default value for optional arguments:

    type T(?arg) =
      member val Arg = defaultArg arg 0
    
    let t1 = T(1) 
    let t2 = T() //t2.Arg is 0
    

提交回复
热议问题