Scala 不处理 ':' 的非显式类型闭包功能
所以基本上我想编写一个可以这样写的函数:
{ println(_) } =: thing
这里我希望它实际执行 thing.=:(println(_))
。为了论证,可以说 =:
具有以下实现:
def =:(block : Int => Any) {
block(5)
}
所以我尝试按照上面的方式调用它,我得到:
<console>:10: error: type mismatch;
found : Unit
required: Int => Any
println(_) =: thing
然后我尝试这样做:
thing.=:(println(_))
这样我得到了一个很好的 5
打印到终端。然后我尝试了这个:
{ value => println(value) } =: thing
这再次失败并告诉我有一个“缺少参数类型”。我猜测这是因为 Scala 在这种情况下首先尝试解析/编译函数参数,并且当它被称为更传统的方式(使用点运算符)。
谁能更清楚地说明这里的问题,并提出实现接近我最初目标的最佳方法?
PS 对不起,这个标题。一旦我更好地理解了问题,我就会重命名它。
So basically I want to write a function that can be written like this:
{ println(_) } =: thing
Here I want it to actually do thing.=:(println(_))
. Lets say for the sake of argument that =:
has the following implementation:
def =:(block : Int => Any) {
block(5)
}
So I try calling it the above way and I get:
<console>:10: error: type mismatch;
found : Unit
required: Int => Any
println(_) =: thing
I then try doing this:
thing.=:(println(_))
This way I get a nice 5
printed to the terminal. I then tried this:
{ value => println(value) } =: thing
This again failed and told me there is a "missing parameter type". I'm guessing that this is because Scala tries to parse/compile the function argument first in this case and doesn't guess the type as it would (I'm completely guessing here) when it is called the more conventional way (with the dot operator).
Could anyone shed more light on the problems here and also maybe suggest the best way to achieve something close to my original goal?
P.S. Sorry about the title. I'll rename it once I have a better understanding of the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类型推断是从左到右进行的,即使
#:
形式的符号方法名称最终是从右到左进行的。如果您实际上只有一种类型,则可以使用辅助方法:但如果您有许多可能的类型签名,则这不是一个完全令人满意的解决方案,因为您必须将左侧的辅助方法名称与右侧所需的类型相匹配。
Type inference works left-to-right, even if symbolic method names of the
#:
form end up working right to left. You can use a helper method if you actually only have one type:but this isn't an entirely satisfactory solution if you have many possible type signatures because you have to match the helper method name on the left to the required type on the right.
那么为什么不添加参数类型呢:
我自己不是 Scala 专家,所以我无法对推理器可以推理什么和不能推理什么提供更深入的解释。
So why don't you add the parameter type:
I'm not a Scala expert myself so I can't provide a deeper explanation of what the inferencer can an cannot inference.