scala =>符號含義總結
阿新 • • 發佈:2018-12-25
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class.
For example, the type Int => String, is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String.
scala> val f: Function1[Int,String] = myInt => "my int: "+myInt.toString
f: (Int) => String = <function1>
scala> f(0)
res0: String = my int: 0
scala> val f2: Int => String = myInt => "my int v2: "+myInt.toString
f2: (Int) => String = <function1>
scala> f2(1)
res1: String = my int v2: 1
scala> val f2: Function2[Int,Int,String] = (myInt1,myInt2) => "This is my function to transfer " + myInt1 + " and " + myInt2 + " as a string component."
f2: (Int, Int) => String = <function2>
scala> f2(1,2)
res6: String = This is my function to transfer 1 and 2 as a string component.
scala> val f22:(Int,Int)=>String = (myInt1,myInt2) => "This is my function to transfer " + myInt1 + " and " + myInt2 + " as a string component."
f22: (Int, Int) => String = <function2>
scala> f22(2,4)
res7: String = This is my function to transfer 2 and 4 as a string component.
Here myInt is binded to the argument value passed to f and f2.
() => T is the type of a function that takes no arguments and returns a T. It is equivalent to Function0[T]. () is called a zero parameter list I believe.
scala> val f: () => Unit =
() => { println("x")}
f: () => Unit = <function0>
scala> f()
x
scala> val f2: Function0[Unit] = () => println("x2")
f: () => Unit = <function0>
scala> f2()
x2 As the most simplified answer, you can substitute whatever is on the left-hand side of => with the word "LEFT" and whatever is on the right-hand side with the word "RIGHT". Then, the meaning of "LEFT => RIGHT" becomes: Take LEFT then do RIGHT. This means that if you have a "()=>" that you can take nothing (that is, no parameters) and then do whatever is on the right-hand side. This is the most common meaning.
f: () => Unit = <function0>
scala> f()
x
scala> val f2: Function0[Unit] = () => println("x2")
f: () => Unit = <function0>
scala> f2()
x2 As the most simplified answer, you can substitute whatever is on the left-hand side of => with the word "LEFT" and whatever is on the right-hand side with the word "RIGHT". Then, the meaning of "LEFT => RIGHT" becomes: Take LEFT then do RIGHT. This means that if you have a "()=>" that you can take nothing (that is, no parameters) and then do whatever is on the right-hand side. This is the most common meaning.