'Kotlin String Concatenation using elvis operator

System.out.println(student != null ? student.name != null ? student.name + " is my mame" : "Name is Null" : "Student is Null ");

I want to concatenate strings if the value is not null. I can do it in java. How to do it in kotlin?



Solution 1:[1]

use safenull (?) and elvis(?:) operator

var output = student?.let{ model ->
           model.name?.let{ nm ->
               "$nm is my mame"
           } ?: "Name is Null"
       } ?: "Student is Null "
       print(output)

Solution 2:[2]

Another thing you could do:

val message = student?.name?.let { "$it is my name" }
    ?: "${ if (student == null) "Student" else "Name"} is null"
println(message)

This is a pretty typical pattern - use chained null checks and do something with the value if you didn't hit a null along the way. If you did, do some default / fallback handling (after the ?: elvis operator).

If that handling needs to be something complicated, the when approach in @Joffrey's answer is probably neater. But this is how you'll often handle stuff nested nullables in a single line - and if you're running an action instead of returning a value, often you won't need a fallback part at all. Just "if I can access this property without hitting a null, do this with it"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gaurav Chaudhari
Solution 2 cactustictacs