简体   繁体   English

返回地图

[英]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. 我了解到最好避免使用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: 如果要检查列表中是否存在满足某些条件的元素,可以使用exists方法:

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): 在这种情况下,您仍然可以使用exists ,但是,如果要调用所有方法,则需要先使用map (假设您的列表很急):

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 : 如果您不需要调用所有方法(如果方法是纯方法,则可能不需要调用所有方法),则可以使用exists

roles.exists { role =>
    userRole.getClass.getDeclaredMethod(role.toString)
            .invoke(userRole).asInstanceOf[Boolean]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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