Reputation: 4113
I have seen some code using the :>
operator to accomplish something similar to type-casting in C#
but even though I've searched a lot online I've seen no documentation about it.
What is that operator used for?
How does it work?
Where can I find some documentation about it?
Upvotes: 4
Views: 140
Reputation: 243041
As @TheInnerLight explains, the :>
operator represents an upcast. If you are coming from C#, this takes a bit of time to get used to, because in C# both (safe) upcast and (unsafe) downcast are written as (SomeType)value
.
In F#, you do not need :>
very often, because the compiler will insert automatic upcasts in the most common places - just like the C# compiler. For example, say we have foo
that takes obj
:
let foo (a:obj) = 0
The F# compiler accepts the following just fine, even though the argument is Random
rather than obj
(as the function foo
expects):
foo (System.Random())
You could write this more explicitly, but you do not have to because the compiler inserts upcast:
foo (System.Random() :> obj)
One case where you need explicit upcasts is when returning different values from different branches of if
or match
constructs. For example:
if true then obj()
else System.Random()
This does not type check and you get an error:
error FS0001: This expression was expected to have type
System.Object
but here has typeSystem.Random
You can fix this with an explicit upcast:
if true then obj()
else System.Random() :> obj
Upvotes: 8
Reputation: 12184
:>
is the upcast operator. It's used to cast upward in an hierarchy so it's a type of casting that can be verified at compile time.
Its counterpart :?>
is the downcast operator but the success of this can only be resolved at runtime.
See this page for more details: https://msdn.microsoft.com/visualfsharpdocs/conceptual/casting-and-conversions-[fsharp]
Upvotes: 9