Scala:生成一个有条件地运行另一个块的块

编程入门 行业动态 更新时间:2024-10-28 16:16:49
本文介绍了Scala:生成一个有条件地运行另一个块的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 Circumflex框架中,您可以将URL映射到如下所示的块:

In the Circumflex framework, you can map an URL to a block like this:

get("/foo") = { "hello, world!" }

当浏览到 / foo ,将按预期显示给定的字符串。现在,要编写完整的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 / 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: daily-scala.blogspot/2009/12/by-name-parameter-to-function.html

更多推荐

Scala:生成一个有条件地运行另一个块的块

本文发布于:2023-11-22 04:08:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615923.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!