If I have a code fragment like ``` val myNullableS...
# announcements
r
If I have a code fragment like
Copy code
val myNullableString : String?
val resultingString = if (myNullableString.isNullOrBlank()) myNullDefaultString else String.format(myNullableString!!, someOtherString)
I have to use
myNullableString!!
in
String.format()
since the compiler would not be able to figure out that
isNullOrBlank()
includes a null-check. Is this correct or is there any way to tell the compiler that a function will infer that the instance is not null?
p
Didn’t hear there is a way to tell such info to compiler, but here is a workaround: having function returning null if string is empty and using let?.{} after that
Copy code
inline fun String?.nullIfBlank(): String? = if (this?.isBlank() ?: true) null else this

val resultingString: String = myNullableString.nullIfBlank()?.let { String.format(it) } ?: myNullDefaultString
r
My question has been more towards a “Kotlin native” way to handle such a case. So also your solution ay work it’s still a “workaround” 😉