Propagating optional arguments

前端 未结 3 1569
难免孤独
难免孤独 2021-02-13 17:11

The following code does not compile.

type A(?arg) =
  member __.Arg : string option = arg

type B(?arg) =
  inherit A(arg) //ERROR expected type string but has t         


        
相关标签:
3条回答
  • 2021-02-13 17:41

    F# spec 8.13.5 Optional arguments to method members

    Callers may specify values for optional arguments by using the following techniques:

    • By name, such as arg2 = 1.
    • By propagating an existing optional value by name, such as ?arg2=None or ?arg2=Some(3) or ?arg2=arg2. This can be useful when building one method that passes optional arguments on to another.
    • By using normal, unnamed arguments matched by position.

      type A(?arg) =
          member __.Arg : string option = arg
      
      type B(?arg) =
          inherit A(?arg = arg) 
      
      printfn "1. %A" (B()).Arg // None
      printfn "2. %A" (B("1")).Arg // Some "1"
      
      printfn "3. %A" (A()).Arg // None
      printfn "4. %A" (A("1")).Arg // Some "1"
      
    0 讨论(0)
  • 2021-02-13 17:57

    Sorry had to test it first: it seems you are right - you have to do the "?" for A yourself:

    type A(arg : string option) =
      new (a) = new A(Some a)
      new () = new A(None)
      member __.Arg : string option = arg
    
    type B(?arg) =
      inherit A(arg)
    
    0 讨论(0)
  • 2021-02-13 17:59

    F# will translate ?-marked arguments to optional values. Providing an argument gives a Some-value while not providing it gives a None-value. The combination of optional and named arguments lets you have huge flexibility.

    See also my answer here https://stackoverflow.com/a/66043023/15143713 /JEE, Sharp#Soft

    0 讨论(0)
提交回复
热议问题