F
F
furyon2018-08-30 04:45:36
Kotlin
furyon, 2018-08-30 04:45:36

How does safe call work in Kotlin?

Hey!
Let's take an example:

val map = HashMap<String, String>()
val str = map["str"]?.trim()?.toLowerCase()

If I understand correctly, trim cannot return null . However, I am forced to use a question mark ( ? ) after it. I thought that as soon as safe call encounters null , null will be returned, otherwise the chain will continue with not null value. But apparently this is not so.
I would be grateful if you tell me how it actually works, and why I have to use safe call after trim (in which case this may come in handy). Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2018-08-30
@furyon

No, that's not how it works.
The result of the expression x?.f() is nullable, and you want to call another function on it. Therefore, another "?" is needed: x?.f()?.g()
In what case can this be useful? The question is unclear, in any case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question