How to implement an interface member that returns void in F#

我怕爱的太早我们不能终老 提交于 2020-01-01 23:59:08

问题


Imagine the following interface in C#:

interface IFoo {
    void Bar();
}

How can I implement this in F#? All the examples I've found during 30 minutes of searching online show only examples that have return types which I suppose is more common in a functional style, but something I can't avoid in this instance.

Here's what I have so far:

type Bar() =
    interface IFoo with
        member this.Bar() =
            void

Fails with _FS0010:

Unexpected keyword 'void' in expression_.


回答1:


The equivalent is unit which is syntactically defined as ().

type Bar() =
    interface IFoo with
        member this.Bar () = ()



回答2:


For general info on F# types, see

The basic syntax of F# - types

From that page:

The unit type has only one value, written "()". It is a little bit like "void", in the sense that if you have a function that you only call for side-effects (e.g. printf), such a function will have a return type of "unit". Every function takes an argument and returns a result, so you use "unit" to signify that the argument/result is uninteresting/meaningless.




回答3:


The return type needs to be (), so something like member this.Bar = () should do the trick




回答4:


The equivalent in F# is:

type IFoo =
    abstract member Bar: unit -> unit


来源:https://stackoverflow.com/questions/3067605/how-to-implement-an-interface-member-that-returns-void-in-f

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