Search code examples
f#implicit-conversion

F# seems to not leverage implicit .NET conversion operators


According to

The following F# code should be legitimate:

[<HttpPost("post-data-2")>]
[<ProducesResponseType(StatusCodes.Status200OK)>]
[<ProducesResponseType(StatusCodes.Status500InternalServerError)>]
member this.PostData2(data: string): Task<ActionResult<int>> = 
    task {
        try 
            return this.Ok(0)
        with | x -> 
            return this.StatusCode(StatusCodes.Status500InternalServerError, -1)
    }

Instead I get two compilation errors in the two 'return' lines

Error FS0193 Type constraint mismatch. The type 'OkObjectResult' is not compatible with type 'ActionResult'

and

Error FS0193 Type constraint mismatch. The type 'ObjectResult' is not compatible with type 'ActionResult'

This works however:

[<HttpPost("post-data-1")>]
[<ProducesResponseType(StatusCodes.Status200OK)>]
[<ProducesResponseType(StatusCodes.Status500InternalServerError)>]
member this.PostData1(data: string): Task<ActionResult<int>> = 
    task {
        try 
            return ActionResult<int>(this.Ok(0))
        with | x -> 
            return ActionResult<int>(this.StatusCode(StatusCodes.Status500InternalServerError, -1)) 
    }

Why are the implicit cast operators not recognized by F#?


Solution

  • Not sure there can be much of an answer besides "because the language designers decided for it to be that way". Implicit conversions are only used in a narrow set of circumstances in F#.

    In addition to calling the constructor as you have, you should also be able to explicitly call ActionResult.op_Implicit or define you own implicit conversion operator.