Reputation: 641
Is it possible to directly return a response inside a map otherwise than doing that:
var authorized = false
roles.map { role =>
val method = userRole.getClass.getDeclaredMethod(role.toString)
authorized = method.invoke(userRole).asInstanceOf[Boolean]
}
authorized
or is it the only way? I've learned that it's better to avoid using var.
Thanks!
Upvotes: 0
Views: 393
Reputation: 27971
If you want to check if there exists an element in your list that satisfies some condition, you can use the exists
method:
list.exists(value => condition(value))
Edit after the question was changed:
You can still use exists
for this case, but if you want to invoke all the methods, you need to use map
first (assuming your list is eager):
roles.map { role =>
userRole.getClass.getDeclaredMethod(role.toString).invoke(userRole)
}.exists(_.asInstanceOf[Boolean])
If you don't need to call all methods (which you probably don't need to if the methods are pure), you can just use exists
:
roles.exists { role =>
userRole.getClass.getDeclaredMethod(role.toString)
.invoke(userRole).asInstanceOf[Boolean]
}
Upvotes: 6