bmarinovic
05/20/2020, 1:42 PMwhen
block (hasMaxRole
is extension method on my User
data class):
if (loggedInUser.hasMaxRole(<http://Role.NO|Role.NO>_ROLE)) {
ResponseEntity(HttpStatus.FORBIDDEN)
} else if (loggedInUser.hasMaxRole(Role.USER_ROLE)) {
if (loggedInUser.id == id) {
ResponseEntity.ok(loggedInUser)
} else {
ResponseEntity(HttpStatus.FORBIDDEN)
}
} else {
userApiService.findById(id)
}
I would like something like this:
when(loggedInUser) {
hasMaxRole(<http://Role.NO|Role.NO>_ROLE) -> ResponseEntity(HttpStatus.FORBIDDEN)
hasMaxRole(Role.USER_ROLE) && (loggedInUser.id == id) -> ResponseEntity.ok(loggedInUser as Any)
hasMaxRole(Role.USER_ROLE) -> ResponseEntity(HttpStatus.FORBIDDEN)
else -> userApiService.findById(id)
}
(even with this code, I am repeating loggedInUser
in second match since I need to call it twice in && operation)Jakub Pi
05/20/2020, 2:40 PMin
operator to check for whether a value belongs to a collection. Assuming Role is an enum or a sealed class, the compiler will check whether you've considered all branches.Jakub Pi
05/20/2020, 2:47 PMwhen(loggedInUser.role) {
NO_ROLE -> ResponseEntity(HttpStatus.FORBIDDEN)
USER_ROLE -> if(id == loggedInUser.id) ResponseEntity.ok(loggedInUser) else ResponseEntity(HttpStatus.FORBIDDEN)
in OTHER_ROLES -> ...
else -> userApiService.findById(id)
}
bmarinovic
05/20/2020, 2:48 PMbmarinovic
05/20/2020, 2:49 PMJakub Pi
05/20/2020, 2:49 PMbmarinovic
05/20/2020, 2:50 PMJakub Pi
05/20/2020, 2:51 PMJakub Pi
05/20/2020, 2:52 PMfun User.canLogin(id : String) : Boolean = id == this.id && this.hasMaxRole(Role.USER_ROLE)
Jakub Pi
05/20/2020, 2:54 PMwhen {}
without an object.Jakub Pi
05/20/2020, 2:57 PMwhen {
loggedInUser.canLogin(loggedInUser.id) -> ...
loggedInUser.role in EnumSet.of(NO_ROLE, USER_ROLE) -> ...
else -> ...
}
bmarinovic
05/20/2020, 2:59 PM