https://kotlinlang.org logo
#language-proposals
Title
# language-proposals
d

Davio

06/27/2022, 8:37 AM
Hi all, I don't know if this is the right channel, but I encountered the function
toDoubleOrNull()
(similar functions exist for other numeric types). This extension function is defined on
String
instead of
String?
Would it make sense to define this function on
String?
instead so a null-valued String just returns null? I noticed that
toBoolean()
is defined on
String?
as well.
r

Rob Elliot

06/27/2022, 8:49 AM
I prefer having to add the null dereferencing ? - it's one character and makes it clear I know the value could be null.
d

Davio

06/27/2022, 8:53 AM
I guess it's a matter of personal preference then, but since toBoolean has it, I thought that there would be a valid precedent, but maybe toBoolean is simpler since only "true" (case insensitive) yields true and everything else (including null) yields false
r

Ruckus

06/27/2022, 3:12 PM
It makes sense for
toBoolean()
because a
null
input is mapped to a different output (
false
in this case). If, however, a
null
input is always a
null
output, there's no reason to accept
null
inputs as the language already has a built in way to handle that in the general case (i.e.
?.
).
5
e

ephemient

06/28/2022, 6:08 AM
I also think
.toBoolean()
isn't a great example anyway; its behavior is a carry-over from Java's
Boolean.parseBoolean
, but unless you need to be precisely compatible with that, I would recommend
.toBooleanStrict()
or
.toBooleanStrictOrNull()
instead
2
3 Views