Kotlin map not null7/14/2023 We need to handle situations where the result is irregular, like NaN. If our average example would operate on lists of Floats or Doubles instead of Ints, this would be the case automatically: The average of an empty list of Doubles would be NaN (not a number) – a built-in result value intended for such operations that cannot work on all inputs.īut there are two drawbacks to this solution: The first is that we still need to check how the result looks like. 2️⃣ Construct a Result TypeĪnother way would be to construct a valid result for the invalid inputs. So this is apparently not the best approach. There might be too much to read or the documentation is unclear or even worse: out of date. But as we all know, consulting the documentation is not always the developer’s first approach. The first and probably easiest way would be to write a comment which specifies the valid inputs. We have a few different options to avoid such unpleasant surprises: 1️⃣ Documentation Especially when it’s not as obvious as in our example which input values are valid and which ones aren’t.įor example, would you be able to tell how valid input arguments look like for this weird looking signature? fun request( It’s not the end of the world, but still pretty annoying. Then suddenly, oh wonder, an arithmetic exception is thrown, and the execution of the program stops. fun List.average() = sum() / sizeĮverything works perfectly well until someone calls this function on an empty list. As a concrete example in Kotlin, let’s have a look at the following average function, where we divide the sum of all elements in a list by the list’s size.
0 Comments
Leave a Reply. |