Hi! I shot myself again with elvis operator. Had ...
# language-evolution
z
Hi! I shot myself again with elvis operator. Had similar bug months ago, but of course forgot it and was debugging it today again 🙃
Copy code
private fun isGroupChatInfoExpired(groupChatInfo: GroupChatInfo): Boolean {
    return Epoch.currentEpoch > (groupChatInfo.epoch ?: 0 + GROUP_CHAT_INFO_VALID_TIME) //epoch is nullable
}
This is always
true
. To fix the problem`groupChatInfo.epoch ?: 0` must be in parenthesis like:
Copy code
private fun isGroupChatInfoExpired(groupChatInfo: GroupChatInfo): Boolean {
    return Epoch.currentEpoch > ((groupChatInfo.epoch ?: 0) + GROUP_CHAT_INFO_VALID_TIME) //epoch is nullable
}
Is it possible to show some warning in IntelliJ (Android Studio) that this will possibly have a wrong evaluation?
e
It might be possible to have an inspection that would add parenthesis on Alt+ENTER. However, it means that if I intended to write
something ?: a + b
, then I'll have to fix it to
something ?: (a + b)
which does not look very nice to my taste.
z
It was logical for me that elvis operator have the highest priority, but I was totally wrong. I'm not saying it's wrong how it is, just that it's dangerous to work without parenthesis, because it maybe doesn't work as it looks on the first sight. God knows how many similar mistakes have all over the project, because it's hard to search for that now.
d
Perhaps there should be a general extension method
orIfNull
(or better named) so that this would be
groupChatInfo.epoch.orIfNull(0)
, so that the
()
go just around the replacement value instead of also in front of
groupChatInfo
.
e
a little hint for the future, if unsure, always put parenthesis and check alt+enter if Intellij suggests you to remove useless parenthesis, if you don't get that, then automatically their presence is vital
âž• 1