Given ```val string: String? = "possibly-null"```...
# codingconventions
s
Given
Copy code
val string: String? = "possibly-null"
Which of the following do people prefer to get either the value or an empty string if it's null?
Copy code
val stringOrEmpty: String = string ?: ""
1️⃣ or
Copy code
val stringOrEmpty: String = string.orEmpty()
2️⃣
1️⃣ 2
2️⃣ 12
The main (only?) reason I can see for
orEmpty()
would be if we wanted to keep chaining stuff on the result. Sort of like
string.orEmpty().capitalize()
or something.
m
I think
orEmpty
conveys the intention better.
2
s
I'm a bit torn, actually. 🌪️
m
I always use
.orEmpty()
if available for consistency. Makes the code more comprehensible than the cryptic
?: ""
esp. in chains longer than a simple
a.onEmpty()
. Also, longer chains would require parenthesis with
(a ?: "").foo()…
. Also, in other scenarios like
?: emptyList()
creating an empty value is quite lengthy.
s
When it comes to chaining, I'm definitely more for
orEmpty()
. The same goes for lists (
.orEmpty()
>
?: emptyList()
).