定义一个函数:
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
本文介绍了Scala中如何定义和使用函数,包括标准函数定义、匿名函数及如何将函数赋值给变量等多种方式。
1463

被折叠的 条评论
为什么被折叠?



