ducktyped ducktyped - 1 year ago 70
Scala Question

What does => and () => mean in Scala

I am new to Scala and I really like it, but sometimes it surprises me. For instance:

clickedCallbacks: List[() => Unit])

Could anyone tell me what
() =>
mean in Scala?

Answer Source

=> 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

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()

scala> val f2: Function0[Unit] = () => println("x2")
f: () => Unit = <function0>

scala> f2()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download