Difference between overloaded f # functions with additional parameters

F # allows overloaded functions to differ only in an optional parameter, for example:

type MyClass() = 
    member this.func(a: string, b:string) = "func(a,b)"
    member this.func(a: string, ?b:string) = "func(a,?b)"

What would you call the first function?

+6
source share
1 answer

I do not think that there is a reasonable way to call the first function if two overloaded functions differ only in an optional parameter. As mentioned in the comments, using this is probably a bad design, and you should rename the options.

As you probably noticed, when you try to call a function in the usual way with MyClass().func("A","B"), you get an error message complaining of ambiguity:

error FS0041: func . . : MyClass.func: a: string *? B: string → string, member MyClass.func: a: string * b: string → string

( ?b) , Some :

MyClass().func("A")
MyClass().func("A",?b=Some "B")

, . , , , , :

let inline callFunc (o:^T) a b = 
  (^T : (member func : string * string -> string) (o, a, b)) 

callFunc (MyClass()) "A" "B"
+8

Source: https://habr.com/ru/post/1016485/


All Articles