Reputation: 11595
What does a colon that's positioned after a tuple but before another type mean within a method signature?
Here's the syntax:
member this.Post (portalId : string, req : PushRequestDtr) : IHttpActionResult =
Here's the context:
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) :> _
Specifically, what does this method signature mean?
Does this method take two parameters or one parameter?
I understand this:
(portalId : string, req : PushRequestDtr)
But I'm confused about this syntax that's appended to the end of it:
: IHttpActionResult
Upvotes: 3
Views: 232
Reputation: 11440
That would be the return type, i.e. the type of the value returned by the method.
From the F# online docummentation:
https://learn.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/members/methods
// Instance method definition.
[ attributes ]
member [inline] self-identifier.method-nameparameter-list [ : return-type ]=
method-body
In this case return_type
is IHttpActionResult
, which means this method will return an object that implements the IHttpActionResult
interface.
Also, although (portalId : string, req : PushRequestDtr)
looks like a tuple (and in a certain way it is syntax-wise) it is not, in fact, treated as a tuple. In this case, this is a specific F# syntax for declaring method arguments while defining a method of a F# object. This is the part represented by method-nameparameter-list
in the F# method template declaration. This means that the Post
method receives two arguments: portalId
and req
, not a single argument as a tuple.
Specifically, this syntax of a list of arguments that looks like a tuple but that they are not a tuple has to be used when declaring method arguments instead of function arguments. The member
keyword is the one that makes this line a method declaration instead of a function declaration.
--
Regarding the :>
operator: This is a cast operator. More specifically a upcasting
operator (which changes the type of a more derived type to the type of some higher type in the type hierarchy).
In this case, it is being used to explicitly tell the compiler that each branch in the match expression will return some type that is derived (or that implements) IHttpActionResult
. I am not quite sure why this cast is needed (something to do with F# not being able to infer the correct type in this context, see this other question: Type mismatch error. F# type inference fail?) but in fact, it is casting every possible return value to IHttpActionResult
which is the method's return type.
https://learn.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/casting-and-conversions
Upvotes: 7