加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

右箭头意义在Scala

发布时间:2020-12-16 19:08:58 所属栏目:安全 来源:网络整理
导读:在 Scala编程的第9章中,有一个这样的示例方法: def twice(op: Double = Double,x: Double) = op(op(x)) 作者在书中说: The type of op in this example is Double = Double,which means it is a function that takes one Double as an argument and return
在 Scala编程的第9章中,有一个这样的示例方法:

def twice(op: Double => Double,x: Double) = op(op(x))

作者在书中说:

The type of op in this example is
Double => Double,which means it is a
function that takes one Double as an
argument and returns another Double.

在这里,在以前的章节中,我不明白什么是“Double =&Do”Doulbe“,其中”=>“出现只意味着功能文字,从来没有像这样写过“Type => Type”,因为根据scala函数的文字语法定义,函数文字的正确部分是函数体,函数体如何可以是“Double”?

解决方法

因为它有两个用法.

首先,你可以使用=>定义函数文字.

scala> val fun = (x: Double) => x * 2
fun: (Double) => Double = <function1>

scala> fun (2.5)
res0: Double = 5.0

这很简单但这里的问题是,什么类型的乐趣呢?这是一个“Double”作为参数并返回一个double“的功能,对吧?

那么我怎么可以注释它的类型的乐趣?那就是(Double)=> (双).那么,以前的例子可以重写为:

scala> val fun: Double => Double = (x: Double) => x * 2
fun: (Double) => Double = <function1>

scala> fun (2.5)                                       
res1: Double = 5.0

好的,那么下面的代码做什么呢?

def twice(op: Double => Double,x: Double) = op(op(x))

那么它告诉你op是(Double => Double),这意味着它需要一个需要Double并返回Double的函数.

所以你可以将以前的乐趣函数传递给它的第一个参数.

scala> def twice(op: Double => Double,x: Double) = op(op(x))    
twice: (op: (Double) => Double,x: Double)Double

scala> twice (fun,10)
res2: Double = 40.0

而且它将相当于用fun替换op,并用x替换x,那就是fun(fun(10)),结果将为40.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读