简体   繁体   中英

Return in a map

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!

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]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM