2010-10-21 33 views
1

F#类定义这是为什么接受:有和没有界面

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

但是,这并不:

type SomeIface = 
    abstract id : int 

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

编译器抱怨我使用“VAL”告诉我使用“成员'但是我不能使用可变的。

回答

4

德斯科的答案是正确的。至于为什么方法不起作用,关键是在F#中,当你有像

interface Iface with 
    [indented lines here] 

缩进行只能包含接口的成员的实现。他们不应该包含额外的字段或您定义的类型的成员(例如您的案例中的两个可变字段)。因此,desco的答案有效,如下所示:

type SomeIface = 
    abstract id : int 

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

上述接口的实现移动领域

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