inheritancef#recordtype

Creating an F# record type with a constant value


Let's say I have a record defined thusly...

type Employee = {Name : string; Salary : int}

and I want another type where Salary is fixed. I'd like to be able to say...

type Manager = {Name: string; Salary : int = 250000}

...but it seems I can't.

What options do I have to get this behaviour?


Solution

  • You can give your record a read-only property:

    type Manager = 
        {
            Name: string
        }
         member this.Salary = 250000
    

    FSI example:

    > let m = { Name = "Foo" };;
    
    val m : Manager = {Name = "Foo";}
    
    > m.Name;;
    val it : string = "Foo"
    > m.Salary;;
    val it : int = 250000