robkuz
robkuz

Reputation: 9914

Upcasting and Generics

I am honestly perplexed about this. Why doesn't that work - aren't I explicitly telling that 'T is indeed a View?

let foo<'T when 'T :> View> (v:'T):View = v

error FS0001: This expression was expected to have type View 
but here has type 'T

Upvotes: 0

Views: 133

Answers (1)

Be Brave Be Like Ukraine
Be Brave Be Like Ukraine

Reputation: 7735

MSDN:

In many object-oriented languages, upcasting is implicit; in F#, the rules are slightly different. 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.

The :> operator performs a static cast, which means that the success of the cast is determined at compile time.

The minimal code would be

let foo<'T when 'T :> View> (v:'T):View = v :> _

Upvotes: 5

Related Questions