views:

69

answers:

2

Why is this acceptable:

type SomeClass<'T> =
    val mutable id : int
    val mutable result : 'T

But this is not:

type SomeIface = 
    abstract id : int

type SomeClass<'T> = 
    interface SomeIface with
        val mutable id : int
        val mutable result : 'T

The compiler complains about my use of 'val' telling me to use 'member' but then I can't use mutable.

+4  A: 

move fields above interface implementation

type SomeIface = 
    abstract id : int

type SomeClass<'T>() = 
    [<DefaultValue>]
    val mutable id : int
    [<DefaultValue>]
    val mutable result : 'T
    interface SomeIface with
        member this.id = this.id

let x = SomeClass<int>(id = 10)
let y : SomeIface = upcast x
printfn "%d" y.id
desco
+4  A: 

Desco's answer is correct. As for why your approach doesn't work, the key is that in F#, when you have something like

interface Iface with
   [indented lines here]

the indented lines can only contain implementations of the interface's members. They should not contain additional fields or members of the type which you are defining (such as the two mutable fields in your case). Therefore desco's answer works, as does something like the following:

type SomeIface = 
    abstract id : int

type SomeClass<'T> = 
    interface SomeIface with
        member this.id = this.id
    val mutable id : int
    val mutable result : 'T
kvb