https://kotlinlang.org logo
#announcements
Title
# announcements
g

Gyuhyeon

11/26/2019, 9:53 AM
I'm still confused about what the "good way" to code in kotlin is, especially when I'm converting from the good ol' java code.
Copy code
// autoconverted from java
    @Transactional
    fun leaveMembership(membershipNo: Long): Boolean {
        val membership = repository.selectOne(membershipNo) ?: return false
        membershipDeletedService.insertExpireHistory(membership)
        repository.delete(membershipNo)
        return true
    }
Copy code
// futile attempt to use as much kotlin stuff
    @Transactional
    fun leaveMembership(membershipNo: Long): Boolean = repository.selectOne(membershipNo)?.let {
        membershipDeletedService.insertExpireHistory(it)
        repository.delete(membershipNo)
        true
    } ?: false
Which is more "kotlin-esque"? Or rather, which code do you think is better? If both are bad, how can it be refactored?
d

diesieben07

11/26/2019, 9:54 AM
I'd much prefer the first one. It shows much more what's happening. In the 2nd one the "false case"is all the way at the end, very far away from the "problem" (no entry found in repo) that causes it
4
m

Mike

11/26/2019, 12:54 PM
To make it easier to read, I might use almost exactly what the Java likely read like, but leveraging that
if
is an expression. There's only one
return
statement, so no 'searching' for returns. Always too many options to choose from 😉
Copy code
val membership = rep.selectOne

return if(membership == null) {
    false 
} else {
    // membership processing here
    true
}
☝️ 1