matthid
matthid

Reputation: 1704

Using unit as Type Parameter and overriding methods

I'm basically asking why the following lines of codes do not compile:

type IGenericType<'a> = 
    abstract member MyFunc : 'a -> 'a -> 'a

type Implementer() = 
    member x.Test () () = () // unit->unit->unit
    interface IGenericType<unit> with 
        member x.MyFunc a b = b // FS0017
        // member x.MyFunc () () = () // FS0017

Just curious if there is a method to make this work as intended. I assume this is a limitation which has to to with the implementation of unit and generics.

Im using the following workaround at the moment:

type Nothing = 
    | Nothing
type Implementer() = 
    interface IGenericType<Nothing> with 
        member x.MyFunc a b = b

Hope someone can bring some light over this behavior.

Upvotes: 2

Views: 126

Answers (1)

pad
pad

Reputation: 41290

You guessed it right. For interoperability inside .NET framework, F# compiler doesn't emit IL for unit but replace it by void instead.

Therefore, your generic interface works on any type but unit. It doesn't seem to be a big problem; your workaround is a nice solution for this issue.

A more detailed discussion can be found in F# interface inheritance failure due to unit.

Upvotes: 2

Related Questions