Carlos Herrera
Carlos Herrera

Reputation: 325

How to add a default value in record type? - F#

I was wondering if it is possible to add an initial value to the property of a type record.

type ToDo = {
   Title : string
   Description : string
   Done : bool
}

Something like this:

Done : bool option = false

That is, I want to do something like in C # :

 public class Todo
    {
        public string Title { get; set; }

        public string Description { get; set; }

        public bool Done { get; set; } = false; // Just like this
    }

Upvotes: 2

Views: 1966

Answers (2)

Guran
Guran

Reputation: 424

An alternative, (only recommended if there are valid defaults for all fields) to Fyodors solution is to use "with" in functions. Like this:

type ToDo = {
   Title : string
   Description : string
   Done : bool
}
module ToDo = 
    let defaultValues = 
        {Title = "Give me a title"; Description = "Describe me"; Done = false}

let myToDoItem = {ToDo.defaultValues with Title = "A real title"; Description = "A real description}

Upvotes: 4

Fyodor Soikin
Fyodor Soikin

Reputation: 80765

No, F# does not have default values for record fields. The usual way to go about this is to provide a "smart constructor" - i.e. a function that takes whatever fields are not default and constructs a record for you:

let toDo title description = 
    { Title = title; Description = description; Done = false }

let firstTodo = toDo "Buy milk" "The cat is hungry"

If you want the API to look nicer, you could also leverage anonymous records:

let toDo (r : {| Title: string; Description: string |}) = 
    { Title = r.Title; Description = r.Description; Done = false }

let firstTodo = toDo {| Title = "Buy milk"; Description = "The cat is hungry" |}

Upvotes: 3

Related Questions