In F# I have a function that returns System.Linq.Expression instances:
and System.Object with
member this.ToExpression() =
match this with
| :? System.Int32 -> Expression.Constant(this) :> Expression
| :? System.Boolean -> Expression.Constant(this) :> Expression
| :? Tml.Runtime.Seq as s -> s.ToExpression()
| _ -> failwith "bad expression"
If I omit the type coercions on the return values F# will infer the return type of the function to ConstantExpression. My first thought was to explicitly mark the return type as being : #Expression, but that didn’t work. Is there a more elegant way of doing this that doesn’t involve manually casting return types to the most generic type?
Thanks.
Edit: Thanks to all of you for the answers. I’ll go with the explicit return type + upcast scenario.
Here are a couple ways you might prefer:
By explicitly stating the return type on the
memberdeclaration, you can then infer it in the body, e.g. via_as a “please infer this type for me” or by using theupcastoperator which will infer the type to up-cast to from the constraints.