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

Scala中函数定义中多个参数子句的要点是什么?

发布时间:2020-12-16 19:01:02 所属栏目:安全 来源:网络整理
导读:我试图理解这个多参数子句的这个语言特征,以及为什么要使用它. 这两个功能有什么区别? class WTF { def TwoParamClauses(x : Int)(y: Int) = x + y def OneParamClause(x: Int,y : Int) = x + y} val underTest = new WTF underTest.TwoParamClauses(1)(1)
我试图理解这个多参数子句的这个语言特征,以及为什么要使用它.
这两个功能有什么区别?

class WTF {
    def TwoParamClauses(x : Int)(y: Int) = x + y
    def OneParamClause(x: Int,y : Int) = x + y
}

>> val underTest = new WTF
>> underTest.TwoParamClauses(1)(1) // result is '2'
>> underTest.OneParamClause(1,1) // result is '2'

在Scala specification at point 4.6这里有一些东西.看看是否对你有意义.

注意:规范称这些“参数子句”,但我认为有些人也可能称之为“参数列表”.

解决方法

以下是多个参数列表的三个实际用途,

>帮助类型推断.这在使用高阶方法时尤其有用.以下,从第一个参数x推断g2的类型参数A,因此可以消除第二个参数f中的函数参数,

def g1[A](x: A,f: A => A) = f(x)
g1(2,x => x) // error: missing parameter type for argument x

def g2[A](x: A)(f: A => A) = f(x)
g2(2) {x => x} // type is inferred; also,a nice syntax

>对于隐式参数.只有最后一个参数列表可以被隐式标记,并且单个参数列表不能混合隐式参数和非隐式参数.以下g3的定义需要两个参数列表,

// analogous to a context bound: g3[A : Ordering](x: A)
def g3[A](x: A)(implicit ev: Ordering[A]) {}

>要根据以前的参数设置默认值,

def g4(x: Int,y: Int = 2*x) {} // error: not found value x
def g5(x: Int)(y: Int = 2*x) {} // OK

(编辑:李大同)

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

    推荐文章
      热点阅读