I'm studying F# and I don't understand the purpose of flexible types, or better, I can't understand the difference between writing this:
set TextOfControl (c : Control) s = c.Text <- s
and writing this:
set TextOfControl (c : 'T when 'T :> Control) s = c.Text <- s
where Control
is the System.Windows.Forms.Control
class.
There is no difference in your example. If return types are constrained, you start seeing the difference:
let setText (c: Control) s = c.Text <- s; c
let setTextGeneric (c: #Control) s = c.Text <- s; c
let c = setText (TreeView()) "" // return a Control object
let tv = setTextGeneric (TreeView()) "" // return a TreeView object
Note that #Control
is a shortcut of 'T when 'T :> Control
.
Type constraints are important to create generic functions for subtypes.
For example,
let create (f: _ -> Control) = f()
let c = create (fun () -> Control()) // works
let tv = create (fun () -> TreeView()) // fails
vs.
let create (f: _ -> #Control) = f()
let c = create (fun () -> Control()) // works
let tv = create (fun () -> TreeView()) // works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With