Reputation:
In the example below, why do these methods have a different type and how do their types differ?
Int => Int //is a shortcut for
Function1[Int, Int].
But why does a method has a different type and what is the difference between (i: Int): Int
and Int => Int
?
Can a function have a similar type like in the first example?
scala> :t def double(i: Int): Int = i * 2
(i: Int): Int
scala> :t def double: Int => Int = i => i * 2
Int => Int
scala> val double2 : Int => Int = i => i * 2
val double2: Int => Int = $Lambda$1197/0x00000008010c8400@54398386
scala> :t double2
Int => Int
Upvotes: 0
Views: 82
Reputation: 2638
In short, Int => Int
is just a syntactic sugar for Function1[Int, Int]
.
A method has a different signature because a method in Scala is just a method in a class just like a Java method. This can have a signature like the one you mentioned: (i: Int): Int
.
On the other hand, Int => Int
is called a function type. The main difference is a function type is an object by itself of type Function1[Int, Int]
. And since an object is a value, a function is also a value.
Now val
functions are concrete instances of Function0
through Function22
and can be composed using andThen
, compose
, and toString
. When you create it like an anonymous function (with no name), the compiler creates an anonymous Function1
instance with an overridden toString
method. That is why you see it differently in the REPL.
Upvotes: 1