Home > Software design >  Kotlin String Concatenation using elvis operator
Kotlin String Concatenation using elvis operator

Time:02-24

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?

CodePudding user response:

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.

CodePudding user response:

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)
  • Related