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?
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?
On
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"
You could do the same as in Java using
ifexpressions, but it's already quite scary with ternaries, so I wouldn't advise doing so (neither in Java nor in Kotlin):Inverting is a tiny bit better but still ugly:
You could also use a mix of
let+ elvis, but that would make it even less readable than theifIMO:So all in all I believe using
whenwould make it a bit clearer: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.