benleggiero
01/28/2018, 2:54 AM?. operator shouldn’t be required when we’ve already verified that we’re not working with a `null`value.
For instance:
// v This proposal focuses on this operator
val isMac1 = System.getProperty("os.name")?.toLowerCase()?.startsWith("mac") ?: false
val osName = System.getProperty("os.name")
val isMac2 = if (osName != null) {
osName.toLowerCase().startsWith("mac")
} else {
false
}
val isMac3 = System.getProperty("os.name")?.let { it.toLowerCase().startsWith("mac") } ?: false
Here, to get the value of isMac1, System.getProperty("os.name") returns a String?, and we used a ?. to handle that. After this operation, we call .toLowerCase() (which returns a String). However, to chain another call (in this case, startsWith("mac") after that, we need to use a ?. operator. This baffles me, since toLowerCase() never returns null, and we can safely assume it was not successfully called on a null object, why does the language require that I use a ?. operator?
To highlight why this baffles me, I use another value, isMac2. The steps to create this are, in my head, identical to the previous. I get the system property, then if it’s not null, I check to see if its lower-case form starts with "mac". If the property was null after all, I use false. Here, toLowerCase() did not require a ?. operator because the compiler inferred that it was unnecessary since we already did a null check. To make isMac1, in my head, we’ve done the same thing, so the same inference should be made.
Just for completion, I included another way to accomplish this with isMac3. I get the system property. If it’s not null, the let block is entered, and its lower-case form is checked to see if it starts with "mac". If that property was null, then false is used. Again, no ?. operator is necessary to use toLowerCase(), since we already know nothing here is null so long as the system property isn’t.
Summary:
If we’re chaining function calls and know for sure that we wouldn’t’ve gotten this far if some ?. had returned null, then further uses of ?. should only be required on functions that return an optional/nullable type.elizarov
01/29/2018, 11:05 AMbenleggiero
01/29/2018, 6:37 PMelizarov
01/29/2018, 6:55 PMbenleggiero
02/01/2018, 1:29 AM