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

4

20

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_.

Borlase answered 18/6, 2010 at 6:25 Comment(0)
P
22

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

type Bar() =
    interface IFoo with
        member this.Bar () = ()
Puparium answered 18/6, 2010 at 6:27 Comment(5)
@Drew - It is an awesome language.Puparium
The C# code was a method, not a property. To reproduce this in F#, I believe you need a member with signature unit -> unit. This would be written "member this.Bar () = ()". Without the unit parameter, the F# could would be a property with a getter.Oestrogen
@Oestrogen - Thanks, it is safe to assume that @Drew implicitly corrected my mistake.Puparium
@Jason, you're right. Actually my method took arguments (and surprisingly wasn't called Bar!) so I'd messed up transcribing it in the original question. Thanks for pointing this out. I'll edit the question.Borlase
@Drew - Wait your method wasn't named Bar? That is a production quality method name... :)Puparium
E
7

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.

Elaina answered 18/6, 2010 at 9:0 Comment(1)
Thanks for the link. I included a quote from the page in your answer.Borlase
S
6

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

Sangsanger answered 18/6, 2010 at 6:30 Comment(1)
To be pedantic, the return type is unit, the only value of that type is spelled ().Elaina
S
3

The equivalent in F# is:

type IFoo =
    abstract member Bar: unit -> unit
Scornik answered 12/4, 2016 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.