本文介绍了Scala 参数模式(喷雾路由示例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,标题含糊不清……不知道如何描述这一点.

Sorry about the vague title...wasn't sure how to characterize this.

我已经在 Scala 中看到/使用了某种代码结构,但我不知道它是如何工作的.它看起来像这样(来自喷雾路由的示例):

I've seen/used a certain code construction in Scala for some time but I don't know how it works. It looks like this (example from Spray routing):

path( "foo" / Segment / Segment ) { (a,b) => {  // <-- What's this style with a,b?
...
}}

在这个例子中,路径中的段分别绑定到关联块内的 a 和 b.我知道如何使用这种模式,但它是如何工作的?为什么它没有将某些东西绑定到foo"?

In this example, the Segements in the path are bound to a and b respectively inside the associated block. I know how to use this pattern but how does it work? Why didn't it bind something to "foo"?

我对喷雾如何实现我的目的不太感兴趣,但这是 Scala 的什么功能,我将如何编写自己的功能?

I'm not so interested in how spray works for my purpose here, but what facility of Scala is this, and how would I write my own?

推荐答案

Senia 的回答有助于理解 Spray-routing 指令以及他们如何使用 HList 来完成他们的工作.但我的印象是你真的只是对

Senia's answer is helpful in understanding the Spray-routing directives and how they use HLists to do their work. But I get the impression you were really just interested in the Scala constructs used in

path( "foo" / Segment / Segment ) { (a,b) => ... }

听起来好像您将其解释为特殊的 Scala 语法,它以某种方式将这两个 Segment 实例连接到 ab.完全不是这样.

It sounds as though you are interpreting this as special Scala syntax that in some way connects those two Segment instances to a and b. That is not the case at all.

path( "foo" / Segment / Segment )

只是对带有单个参数的 path 的普通调用,该表达式涉及对 / 方法的两次调用.没什么特别的,只是一个普通的方法调用.

is just an ordinary call to path with a single argument, an expression involving two calls to a / method. Nothing fancy, just an ordinary method invocation.

该调用的结果是一个函数,它需要另一个函数——当匹配的请求进来时你想要发生的事情——作为参数.这就是这部分的内容:

The result of that call is a function which wants another function -- the thing you want to happen when a matching request comes in -- as an argument. That's what this part is:

{ (a,b) => ... }

它只是一个带有两个参数的函数.第一部分(path 的调用)和第二部分(接收到匹配消息时您想要做什么)在语法上没有任何联系.它们与 Scala 完全分开.但是,Spray 的语义将它们连接起来:第一部分创建了一个函数,当收到匹配的消息时,该函数将调用第二部分.

It's just a function with two arguments. The first part (the invocation of path) and the second part (what you want done when a matching message is received) are not syntactically connected in any way. They are completely separate to Scala. However, Spray's semantics connects them: the first part creates a function that will call the second part when a matching message is received.

这篇关于Scala 参数模式(喷雾路由示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:22
查看更多