https://kotlinlang.org logo
#announcements
Title
# announcements
r

roamingthings

07/26/2017, 6:59 AM
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

pilgr

07/26/2017, 8:15 AM
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

roamingthings

07/26/2017, 8:24 AM
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” 😉
2 Views