Using unit as Type Parameter and overriding methods

試著忘記壹切 提交于 2019-12-11 02:45:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10012078/using-unit-as-type-parameter-and-overriding-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!