Exercise: Safe Division
Change the divide function from throwing an exception to returning Option<Float64>:
- When the divisor is non-zero, return
Some(result) - When the divisor is zero, return
None
Then implement the safeDivide function, using the ?? operator to return a default value of 0.0 when encountering None.
Note
The
?? operator can handle the None case, making code more concise. For example, opt ?? default returns default when opt is None.