Usage scenarios of "=>" in scala
I have always been confused about the use of "=>" in scala, and I don't know what it means. Today, its usage scenarios are listed as follows, and I hope to discuss them together.
-
Indicates the return type of the function (Function Type)
scala> def double(x: Int): Int = x*2 double: (x: Int)Int //定义一个函数变量: scala> var x : (Int) => Int = double x: Int => Int = <function1> //调用 scala> x(2) res1: Int = 4
The type of function double is (x: Int) => Int or Int => Int. The left side is the parameter type, and the right side is the method return value type.
Note: When the function has only one parameter, the parentheses enclosing the function parameters in the function type can be omitted.
-
Anonymous function
//通过匿名函数定义一个函数变量xx scala> var xx = (x: Int) => x + 1 xx: Int => Int = <function1> //给一个高阶函数,传递一个函数: scala> val newList = List(1,2,3).map { (x: Int) => x * 2 } newList: List[Int] = List(2, 4, 6)
Anonymous function definition, the left side is the parameter, the right side is the function implementation body (x: Int)=>{}