Scala:生成一个有条件地运行另一个块的块 [英] Scala: Generate a block that conditionally runs another block
问题描述
在 Circumflex框架中,您可以将URL映射到如下所示的块:
In the Circumflex framework, you can map an URL to a block like this:
get("/foo") = {
"hello, world!"
}
当浏览到 / foo $时, c $ c>,将按预期显示给定的字符串。现在,要编写完整的Web应用程序,几乎总是需要某种形式的身份验证和授权。我正在尝试为上述结构编写某种包装,所以我可以这样写:
which, when browsing to /foo
, will show the given string as expected. Now, to write a complete web application, you almost always need some form of authentication and authorisation. I'm trying to write some kind of wrapper for the above construct, so I can write this:
get("/foo") = requireLogin {
"hello, world!"
}
requireLogin
方法然后将检查用户是否已登录,如果是,则执行给定的块。但是,如果没有,它应该重定向到登录页面。
The requireLogin
method would then check if the user is logged in, and if yes, execute the given block. If not, however, it should do a redirect to the login page.
现在我不知何故不能正确使用语法(我仍然是Scala新手)。
Now I somehow can't get the syntax right (i'm still a Scala newbie). How would you do this in a generic fashion?
推荐答案
尝试如下操作:
def executeMaybe[A](work: => A): Option[A] =
if (util.Random.nextBoolean)
Some(work)
else
None
这将以0.5的概率执行传递的代码,返回 Some(<工作交付的结果>)
或返回无
的情况是其他情况。您可以这样称呼它:
This executes the passed code with probability 0.5, returning Some(<result delivered by work>)
, or returns None
is the other cases. You can call it either like this:
val v = executeMaybe(42)
或带有块符号:
val v = executeMaybe {
// do some work
// provide return value
}
诀窍是使用 by-name参数,该参数由 =>
符号表示。阅读更多此处: http://daily-scala.blogspot .com / 2009/12 / by-name-parameter-to-function.html
The trick is to use a by-name parameter, signalled by the =>
symbol. Read more e.g. here: http://daily-scala.blogspot.com/2009/12/by-name-parameter-to-function.html
这篇关于Scala:生成一个有条件地运行另一个块的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!