vidi
vidi

Reputation: 2106

Passing "unit" as type parameter to generic class in F#

I have an interface which takes a generic parameter and has an abstract method

type MyInterface<'a> =
    abstract member abstractMethod: 'a -> 'a

...and I have a derived class which inherits from base class using unit for the type parameter

type Derived() =
    interface MyInterface<unit> with
        override this.abstractMethod (_) = ()

but the compiler complains that

Error The member 'abstractMethod : unit -> unit' does not have the correct type to override the corresponding abstract method.

If I use another type instead of unit, int for example, the code compiles.

Is this a bug in the compiler? Is there a workaround for it?

Thanks!

Upvotes: 3

Views: 676

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

unit is "special" in terms of interop: when a function takes a unit as parameter, it is compiled to IL as a parameterless function, and when a function returns a unit as result, it is compiled as a void function. As a result of this trickery, you can't really use unit as a "general-purpose" type in interop settings (such as classes and interfaces).

In fact, when I try to compile your code on my machine, I get a different error:

The member 'abstractMethod : unit -> unit' is specialized with 'unit' 
but 'unit' can't be used as return type of an abstract method
parameterized on return type.

Which is trying to say roughly what I described above.

(I'm not sure why you're getting what you're getting; perhaps you're using an older version of F#)

Upvotes: 4

Related Questions