I have a generic function where it's easy to get the compiler to infer the wrong type parameters. The type parameters only control the return type, and if I accidentally miss off a type annotation, the compiler infers obj
.
How can I make it a compile-time error to call my function without giving it explicit type parameters? The Unchecked.defaultof
function works the way I'd like:
> Unchecked.defaultof;;
Unchecked.defaultof;;
^^^^^^^^^^^^^^^^^^^
stdin(1,1): error FS0685: The generic function 'defaultof' must be given explicit type argument(s)
The defaultof
function uses a special attribute. The F# source code is, once again, useful. The implementation of the function is in prim-types.fs
, but the attribute is added in the interface file prim-types.fsi
. A combined declaration would be:
[<RequiresExplicitTypeArguments>]
let inline unsafeDefault<'T> : 'T = (# "ilzero !0" type ('T) : 'T #)
The inline IL (# ... #)
is limited to F# core, but the declaration is something anybody can use.
You can find the attribute in section 16 (page 217) of the F# specification:
When applied to an F# function or method, indicates that the function or method must be given explicit type arguments when used. For example,
typeof<int>
. This attribute should be used only in F# assemblies.
RequiresExplicitTypeArgumentsAttribute should help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With