I think you have to cast the object to the interface type :

1
do printf "%s\n" (newTest:>ITest).Print 

The way round is to inherit (but then you can only inherit from one class...)

By on 10/2/2007 10:47 AM ()

Hi,
Just one small note - this topic was already discussed here: [link:cs.hubfs.net], so you can find some useful information there. Especially the object expression syntax may be interesting for you - It makes it easier to implement an interface in a case where you just need to return an object implementing it from a function, but you don't need to add any other members. For example like this:

(copying a sample from a referenced Don's message)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#light

type InterfaceA = interface 
    abstract getAddress : unit -> string
    abstract setAddress : string -> unit
end

let ConcreteInterfaceA(v) = 
    let address = ref v
    { new InterfaceA with 
        member x.getAddress() = !address
        member x.setAddress(v) = address := v }

// and then use it...
let a = ConcreteInterfaceA("address1");
a.getAddress()
....
By on 10/2/2007 10:57 AM ()

One more thing :-) If you're looking for a workaround, you can either add a member with the same name and hide the casting to an interface type there like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
#light

// in #light syntax we can omit interface & class keywords
type ITest = 
  abstract Print : unit -> string

type Test() =
  interface ITest with
    member this.Print() = "Test"
  // the publicly visible member
  member this.Print() = (this :> ITest).Print()

let newTest = new Test()
do printf "%s\n" (newTest.Print())

Or another option is to write the implementation as a local function and call it from both two members (which I think looks better and you don't have to do the casting):

1
2
3
4
5
6
7
8
 
type Test() =
  let print () = 
    // ...
    "Test"
  interface ITest with
    member this.Print() = print()
  member this.Print() = print()
By on 10/2/2007 12:40 PM ()

Thank you for your replies.

By on 10/3/2007 6:42 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper