scala高级语法之柯里化(curring)和 隐式转换(implicit)

版权声明:耕种 by 会种地的DT男 https://blog.csdn.net/weixin_42617530/article/details/83151923

柯里化(curring)和 隐式转换(implicit)

  • 柯里化(curring)

scala 中 curring 是将一个正常的方法转换为科里化的一个过程
把一个参数列表中的多个参数转换为多个列表
如:①→②

① def m1(a:Int,b:Int)=a+b
② def m2(a:Int)(b:Int) =a+b
  • 隐式转换(implicit)
object Implicit{
def main(args:Array[String]):Unit={
 
implicit val a:Int=10
def m1(a:Int,b:Int)=a+b
def m2(a:Int)(implicit b:Int)=a+b
 
/*def m2(a:Int)(implicit b:Int=1)=a+b*/ //方法参数列表里默认隐式值
println(m2(5))
}
}

隐式转换的注意事项:
①隐式参数值是从上下文环境中寻找,匹配使用implicit修饰的变量,且最多只有一个,与方法参数列表中隐式类型一致,并使用。
②如果匹配到多个,报错。
③如果上下文中没有,则使用方法参数列表中的默认隐式值。
④如果没有默认值,报错。
⑤一个参数列表中只能有一个implicit关键字,implicit放到最后一个列表中,并修饰该列表中的所有参数,如:

def m2(a:Int)(b:Int)(implicit c:Int,d:Int)

案例

implicitval scala:Int=20
 def m3(a:Int)(b:Int)(implicit c:Int,d:Int)=a+b+c+d
println(m3(5)(5))//结果为 50=5+5+20+20

其中 c,d都从上下文中获得20的值

猜你喜欢

转载自blog.csdn.net/weixin_42617530/article/details/83151923