pooiqowiqo
pooiqowiqo

Reputation: 11

Why a type method that should return a string returns a 'unit -> string' instead and how to solve it?

So I have this simple code, I'm trying to figure out classes and inheritance in F#:

type Mkp() =
    abstract tX : unit -> string
    default this.tX() = ""

type A(n : string, v : string) =
    inherit Mkp()
    member this.n = n
    member this.v = v
    override this.tX() = sprintf "%s = \"%s\" " this.n this.v

let test = A "first" "second"
let xxx = "" + test.tX

I get the compiler error: The type 'string' does not match the type 'unit -> string' but I expected test.tX to be a string, what am I doing wrong?

Upvotes: 1

Views: 62

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243096

Your class definitions are correct, but there are two small issues when you use them:

  • When creating the instance, you need to pass parameters to the constructor as a tuple
    i.e. you need to say A("one", "two") rather than A "one" "two"

  • When invoking a method, you need to specify empty parameter list i.e. test.tX()

The correct use of your class A looks like this:

let test = A("first", "second")
let xxx = "" + test.tX()

Upvotes: 6

Related Questions