colinfang
colinfang

Reputation: 21717

Why upcast is not necessary in this let bound function?

According to MSDN

Upcasting is applied automatically when you pass arguments to methods on an object type. However, for let-bound functions in a module, upcasting is not automatic, unless the parameter type is declared as a flexible type.

But

type C() =
    member this.T() = ()
type D() =
    inherit C()

let myfun (x: C)=
    ()

let d = D()

myfun d

I don't need to upcast at all.

Upvotes: 0

Views: 115

Answers (1)

Gus
Gus

Reputation: 26174

Have a look at the F# spec where it says:

This means that F# functions whose inferred type includes an unsealed type in argument position may be passed subtypes when called, without the need for explicit upcasts. For example:

(The example showed there is almost the same as yours)

Also note that for let bound functions upcasting is automatically except in some cases, for example when the argument is composed, if your function was:

let myfun (x: C option)=
    ()

upcast is no longer automatically.

Upvotes: 4

Related Questions