0

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 !!

1
  • 1
    What do you want html to be set to if response.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. Commented Oct 1, 2019 at 8:04

2 Answers 2

6

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) }
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.