scala By-name-parameter 和 Function type的区别

 我来答
xiangjuan314
2016-04-13 · TA获得超过3.3万个赞
知道大有可为答主
回答量:2.9万
采纳率:0%
帮助的人:2902万
展开全部
原来By-name-parameter和函数类型是不一样的概念,以前还以为By-name-paramete 就是函数类型的一个用法呢

By-name-parameter to Function
Today's topic is related to Defining Custom Control Structures. By name parameters are not function objects in the same way as other functions. Normally you need to invoke a function:
scala> def exec(func: () => Int) = func()
exec: (() => Int)Int
// exec invokes the function so 10 is the result
scala> exec (() => 10)
res1: Int = 10
scala> def exec(func: () => Int) = func
exec: (() => Int)() => Int
// here exec returns the function:
scala> exec (() => 10)
res2: () => Int = <function>

Compare that to a by-name-parameter function:

scala> def exec(func: => Int) = func
exec: (=> Int)Int
// by-name-parameters are executed when they are referenced
// so the result is 10
scala> exec {10}
res3: Int = 10
// This is not legal because by-name-parameters
// are not normal functions
scala> def exec(func: => Int) = func()
<console>:4: error: func of type Int does not take parameters
def exec(func: => Int) = func()

So the issue is how can you pass a by-name-parameter to a method that takes a function as a parameter without having to do:

scala> def takesFunc(func: () => Int) = println(func())
takesFunc: (() => Int)Unit
scala> def send(x: => Int) = takesFunc(() => x)
send: (=> Int)Unit
scala> send{2}
2

the alternative syntax is:

scala> def send(x: => Int) = takesFunc (x _)
send: (=> Int)Unit
scala> send {2}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式