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
defaultoffunction uses a special attribute. The F# source code is, once again, useful. The implementation of the function is inprim-types.fs, but the attribute is added in the interface fileprim-types.fsi. A combined declaration would be: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: