The purpose of this post is to provide you with a simple working example of creating different default value sets assigned to a particular record type in F#. It then demonstrates how to update selected fields when binding that default to a new variable using the with keyword.
The benefit of this approach is that the record type remains immutable. Record types do not support the DefaultValueAttribute so it would mean not needing to go out of your way to create a class with mutable explicit fields.
Below is an example of a Meal record type with two different value bindings, one named defaultBreakfastMeal and the other defaultDinnerMeal. There is nothing syntactically different between a regular binding of a record type and one we choose to use as a default.
Record Type & Default Sets
type Meal = {
Food: string
Drink: string }
let defaultBreakfastMeal: Meal = {
Food = "Pastry"
Drink = "Coffee" }
let defaultDinnerMeal: Meal = {
Food = "Shepherd's Pie"
Drink = "Water" }
We can later set a new binding but update the returning default values with selected overrides. In this case, the Food value.
let HangoverMeal = {
defaultBreakfastMeal
with
Food = "Irish Breakfast"
}
Output
HangoverMeal.Food = "Irish Breakfast"
HangoverMeal.Drink = "Coffee"
Top comments (0)