Tomas Jansson
Tomas Jansson

Reputation: 23462

Is it possible to force record type in F# when doing an assignment?

To explain I think it is best with an example:

type myRec = {x: string}
type myRec2 = {x: string}
let x = {x = "hello"}
let y(a: myRec) = a.x
y(x);;

  y(x);;
   --^

error FS0001: This expression was expected to have type
    myRec    
but here has type
    myRec2

So how do I force x to have the type myRec if both myRec and myRec2 has the same signature?

Upvotes: 3

Views: 132

Answers (2)

ildjarn
ildjarn

Reputation: 62975

let x = { myRec.x = "hello" }
// or
let x:myRec = { x = "hello" }
// or
let x = { x = "hello" } : myRec

Further details and examples are available in the documentation.

EDIT: Incorporated alternatives from comments.

Upvotes: 11

Richard
Richard

Reputation: 108975

Yes you can:

let x = { new myRec() with x = "hello" }

use and to assign more fields:

let x = { new myRec3() with x = "hello" and y = "bye" }

Upvotes: 2

Related Questions