In Kotlin, if I have the following:
val html = response.body()?.string()
html will compile to be nullable. I need to pass this to a function that does not allow nullables. Is there a way to pass it (or convert it) in a way that doesn't use !!
You can either pass a default value, by using the elvis operator:
val html = response.body()?.string() ?: ""
nonNullableFunction(html)
Or, you could use let to call it only if html is not null. This will give you a nullable result from the function.
val result = response.body()?.string()?.let { nonNullableFunction(it) }
You can use ?: to declare a default value that will be passed instead of url if url is null:
foo(url?: "default value")
You could also put this in your declaration so html will not be nullable:
val html = response.body()?.string()?: "default value"
As marstran pointed out you can also call your function inside a let block so it will only be called if html is not null:
html?.let{ foo(it) }//it is non-null
htmlto be set to ifresponse.body()returns null? That's why the expression could currently return null, and that's what you'll have to consider before you can work out what to change.