scala学习笔记:理解函数

定义一个函数:

scala> def foo(x:Int)=x*2
foo: (x: Int)Int

可以采用匿名参数:

scala> def foo:((Int)=>Int) = _*2
foo: Int => Int

这个函数的类型是Int=>Int:

scala> var bar = foo _
bar: Int => Int = <function1>

scala> var bar:(Int)=>Int = foo
bar: Int => Int = <function1>

可以直接定义指向匿名函数的变量:

scala> var foo = (x:Int)=>x*2
foo: Int => Int = <function1>

如下代码也可以达到同样的效果:

scala> def foo = (x:Int)=>x*2
foo: Int => Int

scala> def foo(x:Int)=x*2
foo: (x: Int)Int

但个人觉得(待证实),第一种写法相当于先定义了一个匿名函数,然后再赋值给foo

原文地址:https://www.cnblogs.com/bluejoe/p/5115870.html