exceptionf#option-type

`Option.defaultValue` not working properly in f# when raising exception


I am trying to combine Option.defaultValue with failWith to get exception for None values:

printf "%A" (Some 1 |> Option.defaultValue (failwith "Error"))

But this code raise exception for any value.

Why is it?

Is there any way to do this except for match with?


Solution

  • Option.defaultValue takes a value, so your failwith ... is evaluated eagerly.

    I think you would be better with Option.defaultWith which takes a function that is only evaluated if the default is needed.