Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Option Chaining instead of if/else

Tags:

kotlin

Is there a more succint way to write the following code using option chaining and/or the elvis operator?

email.addSubject(if (creator != null)  String.format( inviteDescription, creator) else String.format(inviteDescriptionNoCreator, group))

It feels like there should be.

like image 232
thesilverbail Avatar asked Sep 05 '25 09:09

thesilverbail


1 Answers

Using the normal IF expression

val subject = if (creator != null) {
    inviteDescription.format(creator)
} else {
    inviteDescriptionNoCreator.format(group)
}
email.addSubject(subject)

The Elvis Operator

val subject = creator?.let {
    inviteDescription.format(it)
} ?: inviteDescriptionNoCreator.format(group)
email.addSubject(subject)

If the goal is to write the shortest code possible then you could go with a single line Elvis operator. But if the goal is a readable code, I would choose the simple if expression or a multi line Elvis operator. I would even go one step ahead and move it to a separate method. But whatever you choose, please don't write everything in a single long line, rather put it in separate lines.

like image 73
Henry Avatar answered Sep 08 '25 12:09

Henry