Scott Nimrod
Scott Nimrod

Reputation: 11595

What does it mean to upcast a value to the _ wildcard?

What does it mean to implement a wildcard at the end of a case statement?

Take the following syntax:

match imp req with
| Success () -> this.Ok () :> _

Is this the same as:

| Success () -> this.Ok () :> IHttpActionResult

What is the advantage of writing that type of syntax?

Here's the context of my question:

type PushController (imp) =
    inherit ApiController ()

    member this.Post (portalId : string, req : PushRequestDtr) : IHttpActionResult =
        match imp req with
        | Success () -> this.Ok () :> _
        | Failure (ValidationFailure msg) -> this.BadRequest msg :> _
        | Failure (IntegrationFailure msg) ->
            this.InternalServerError (InvalidOperationException msg) :> _

Upvotes: 3

Views: 78

Answers (1)

Sergio Acosta
Sergio Acosta

Reputation: 11440

The operator :> performs an static upcast to the type specified by the expression to its right side. The syntax for this operator is:

:> expression

That would be, for your example:

some_value :> IHttpActionResult

this tells the compiler that some_value is in fact an object that implements IHttpActionResult.

But according to the F# documentation:

When you use the upcast operator, the compiler attempts to infer the type you are converting to from the context. If the compiler is unable to determine the target type, the compiler reports an error.

https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/casting-and-conversions-%5Bfsharp%5D

Because the only type that can be returned by the Post method is IHttpActionResult, you can let the compiler infer it.

So, in this context this:

:> _

Is equivalent to:

:> IHttpActionResult

Upvotes: 7

Related Questions