2 回答
TA贡献1794条经验 获得超7个赞
我不确定,但也许一些重构会有所帮助。例如,您似乎正在对request数据库使用某种形式,如果根据参数进行填充,那么也许可以像这样进行管理。
fun getMessages(name: String, pageable: Pageable, locale: String?, subject: String?,
recipient: String?): Page<MessageDTO>? {
val request = where(hasMessageName(name))
locale?.let{ request.and(hasLocale(it)) }
subject?.let{ request.and(hasSubject(it)) }
recipient?.let{ request.and(hasRecipient(it))}
return messageRepository.findAll(request, pageable)
.map { messageMapper.toMessageDTO(it) }
.takeIf { it.content.isNotEmpty() }
}
在这里,我不确定.and()方法是如何工作的,所以也许它应该是这样的: request = request.and(...)
TA贡献1853条经验 获得超18个赞
您可以if
用一个when
语句替换您的语句,以便更容易阅读:
fun getMessages(name: String, pageable: Pageable, locale: String?, subject: String?,
recipient: String?): Page<MessageDTO>? = when {
!locale.isNullOrEmpty() && !subject.isNullOrEmpty() && !recipient.isNullOrEmpty() ->
messageRepository.findAll(where(hasMessageName(name).and(hasLocale(locale!!)
.and(hasSubject(subject!!).and(hasRecipient(recipient!!))))), pageable)
!locale.isNullOrEmpty() ->
messageRepository.findAll(where(hasMessageName(name).and(hasLocale(locale!!))), pageable)
!subject.isNullOrEmpty() ->
messageRepository.findAll(where(hasMessageName(name).and(hasSubject(subject!!))), pageable)
else ->
messageRepository.findAll(where(hasMessageName(name)), pageable)
}.map { messageMapper.toMessageDTO(it) }.takeIf { it.content.isNotEmpty() }
添加回答
举报