匿名函数上的 scala By-name 参数 [英] scala By-name parameter on a anonymous function
问题描述
我正在努力编写一个带有 by-name 参数的匿名函数.这就是我累了.
I'm struggling to write an anonymous function with by-name parameter. Here is what i tired.
val fun = (x: Boolean, y: =>Int) => if(x) y else 0
此操作失败并出现以下错误.
This fail with following error.
Error:(106, 31) identifier expected but '=>' found.
val fun = (x: Boolean, y: =>Int) => if(x) y else 0
^
Error:(109, 3) ')' expected but '}' found.
}
^
与标准函数相同的代码如何工作.
How ever same code as a standard function works.
def fun1(x: Boolean, y: =>Int) = if(x) y else 0
有什么指点吗?
---------------编辑-----------------
---------------Edit-----------------
我遇到了一个由两部分组成的问题.senia 的回答解决了最初的案例.假设我有一个函数需要一个函数.
I had a two part problem. senia answer solved the initial case. Suppose I have a function takes a function.
def xxx[A,B](f:(A,=>B)=>B)={}
根据 senia 解决方案,它可以工作.
As per senia solution it works.
val fun: (Int, =>Boolean) => Boolean = (x, y) => y
xxx[Int,Boolean](fun)
但是我想摆脱中间的乐趣并使用匿名函数调用xxx.做
However I wanna get rid of the intermediate fun and call xxx with anonymous function. Doing
xxx((Int, =>Boolean) => Boolean = (x, y) => y)
不会工作.任何想法如何做到这一点?
Will not work. Any ideas how to do this ?
推荐答案
你可以指定匿名函数的类型,而不是像这样的参数类型:
You could specify type of anonymous function, instead of types of parameters like this:
val fun: (Boolean, => Int) => Int = (x, y) => if(x) y else 0
scala> fun(false, {println("!"); 2})
res1: Int = 0
scala> fun(true, {println("!"); 2})
!
res2: Int = 2
<代码>=>Int 不是正确的类型名称,它是方法声明或匿名函数类型的参数块中按名称参数的特殊语法.
=> Int
is not a correct type name, it's a special syntax for by-name parameters in parameters block of method declaration or anonymous function type.
参见 SLS 4.6 函数声明和定义强>
ParamType ::= Type
| ‘=>’ Type
| Type ‘*’
如果您不想将匿名函数分配给变量,您可以使用如下类型推断:
In case you don't want to assign anonymous function to variable you could either use type inference like this:
xxx[Int, Boolean]{ (x, y) => y }
或者这样指定它的类型:
Or specify its type this way:
xxx({ (x, y) => y }: ((Int, => Boolean) => Boolean))
这篇关于匿名函数上的 scala By-name 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!