Siddhant
Siddhant

Reputation: 25

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?

Upvotes: 1

Views: 2717

Answers (3)

cactustictacs
cactustictacs

Reputation: 19544

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"

Upvotes: 2

Gaurav Chaudhari
Gaurav Chaudhari

Reputation: 145

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)

Upvotes: 2

Joffrey
Joffrey

Reputation: 37710

You could do the same as in Java using if expressions, but it's already quite scary with ternaries, so I wouldn't advise doing so (neither in Java nor in Kotlin):

val text = if (student != null) if (student.name != null) "${student.name} is my name" else "Name is null" else "Student is null"
println(text)

Inverting is a tiny bit better but still ugly:

val text = if (student == null) "Student is null" else if (student.name == null) "Name is null" else "${student.name} is my name"
println(text)

You could also use a mix of let + elvis, but that would make it even less readable than the if IMO:

val text = student?.let { s -> s.name?.let { "$it is my name" } ?: "Name is null" } ?: "Student is null"
println(text)

So all in all I believe using when would make it a bit clearer:

val text = when {
    student == null -> "Student is null"
    student.name == null -> "Name is null"
    else -> "${student.name} is my name"
}
println(text)

Note that it might be more appropriate to avoid such proliferation of nulls in the first place. It seems weird that the student name can be null here for instance, maybe it should just not be possible to create a student without a name in the first place.

Upvotes: 3

Related Questions