选项链接而不是if / else

有没有更简洁的方式来使用选项链接和/或elvis运算符来编写下面的代码?

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

感觉应该有。

使用正常的IFexpression式

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

猫王操作员

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

如果目标是尽可能地写出最短的代码,那么你可以使用一个单行的Elvis算子。 但是如果目标是一个可读的代码,我会选择简单的expression式或者多行的Elvis操作符。 我甚至会前进一步,并将其转移到一个单独的方法。 但是不管你选择什么,请不要把所有的东西都写成一行,而是把它放在单独的行中。

只是利用?.?:给了我们以下内容:

 email.addSubject(creator?.let { String.format(inviteDescription, it) } ?: String.format(inviteDescriptionNoCreator, group)) 

不幸的是,这仍然是相当长的,可以说是不容易阅读。 你可以通过使用String.format扩展函数来更多一点的String.format

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