Scala中函数定义中的多个参数子句有什么意义? [英] What is the point of multiple parameter clauses in function definitions in Scala?

查看:123
本文介绍了Scala中函数定义中的多个参数子句有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解多参数子句的这种语言特性的重点,以及为什么你会使用它。
例如,这两个函数的区别是什么?

  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)//结果是'2'
>> underTest.OneParamClause(1,1)//结果是'2'

第4.6点的Scala规范。看看这对你是否有意义。



注意:规范调用了这些'参数子句',但我认为有些人也可能称它们为'参数列表'。

解决方案

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


  1. 帮助类型推断。这在使用更高阶的方法时特别有用。下面,根据第一个参数 x g2 的类型参数 A c $ c>,所以第二个参数 f 中的函数参数可以被省略,

      def g1 [A](x:A,f:A => A)= f(x)
    g1(2,x => x)//错误:缺少参数类型参数x

    def g2 [A](x:A)(f:A => A)= f(x)
    g2(2){x => x} //类型被推断;还有一个很好的语法


  2. 隐式参数。只有最后一个参数列表可以标记为隐式,并且单个参数列表不能混合隐式和非隐式参数。下面定义 g3 需要两个参数列表,

      //类似到上下文绑定:g3 [A:排序](x:A)
    def g3 [A](x:A)(隐式ev:排序[A]){}

     

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



I'm trying to understand the point of this language feature of multiple parameter clauses and why you would use it. Eg, what's the difference between these two functions really?

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' 

There's something on this in the Scala specification at point 4.6. See if that makes any sense to you.

NB: the spec calls these 'parameter clauses', but I think some people may also call them 'parameter lists'.

解决方案

Here are three practical uses of multiple parameter lists,

  1. To aid type inference. This is especially useful when using higher order methods. Below, the type parameter A of g2 is inferred from the first parameter x, so the function arguments in the second parameter f can be elided,

    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
    

  2. For implicit parameters. Only the last parameter list can be marked implicit, and a single parameter list cannot mix implicit and non-implicit parameters. The definition of g3 below requires two parameter lists,

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

  3. To set default values based on previous parameters,

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

这篇关于Scala中函数定义中的多个参数子句有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆