开发者

why is the implementation of my abstract member not public

开发者 https://www.devze.com 2023-03-12 04:13 出处:网络
I\'ve been struggling to get this to compile for about an hour.It must be something stupid.Can you spot it?

I've been struggling to get this to compile for about an hour. It must be something stupid. Can you spot it?

in my lib project:

namespace TravelerStuff
open System

type Traveler =         
    abstract GetData : unit -> unit

type public DeltaTraveler() =
    interface Traveler with
         member v.GetData () =

        printf "hello"

and in my console test app:

[<EntryPoint>] let main _ =
    let traveler = new TravelerStuff.DeltaTraveler()
    traveler.GetData // this line won't compile: (The field, cons开发者_如何学编程tructor or member 'GetData' is not defined)


As gradbot says, F# doesn't currently implicitly convert values to interfaces when searching for members. Also, F# only uses explicit interface implementation (as known from C#) and not implicit implementation where members are not only compiled as implementation of an interface, but also as ordinary (directly visible) members of the type.

Aside from casting, you can duplicate the member in the type definition:

type DeltaTraveler() =    
  member v.GetData () = printf "hello"
  interface Traveler with
    member v.GetData () = v.GetData() 

Also, if you just want to implement an interface, but don't need to add any members, you can use F# object expressions (which are more lightweight):

let deltaTraveler() =
  { new Traveler with
      member v.GetData () = printf "hello" }

// The function directly returns value of type 'Traveler'
let t = deltaTraveler()
t.GetData()


You need to upcast. F# currently won't do it for you in this situation.

(traveler :> TravelerStuff.Traveler).GetData()

// open the namespace to reduce typing.

open TravelerStuff
(traveler :> Traveler).GetData()

Snip from F# docs.

In many object-oriented languages, upcasting is implicit; in F#, the rules are slightly different. Upcasting is applied automatically when you pass arguments to methods on an object type. However, for let-bound functions in a module, upcasting is not automatic, unless the parameter type is declared as a flexible type. For more information, see Flexible Types (F#).

0

精彩评论

暂无评论...
验证码 换一张
取 消