I'm having a bit of a brain freeze with `firstOrNu...
# getting-started
v
I'm having a bit of a brain freeze with
firstOrNull
and a function that could return a nullable string. It's always returning an empty string when I'd rather it return a null:
Copy code
private fun KSAnnotation.getArgumentValue(name: String): String? {
        // I want to return null if the argument is not found, otherwise return the value as a string
        return this.arguments.firstOrNull { it.name?.asString() == name }?.value?.toString() ?: null
    }
Intellij tells me that the
?: null
is useless. But I really would like to return null and not an empty string.
t
?: use the right part only if it's null, so you are writing if it's null return null. So as IJ says it's useless.
v
My brain has unfrozen. I had default values of empty strings so even when no value was supplied, they were empty strings not null.
w
If you want to handle the empty case, you can write
.ifEmpty { null }
💯 1