Simplified code by using `when` instead of `if`.