Reputation: 17785
I can understand this:
scala> def f(i: Int) = "dude: " + i
f: (i: Int)java.lang.String
scala> f(3)
res30: java.lang.String = dude: 3
It defines a function f that takes an int and returns a string that is of the form dude: + the int that is passed in.
Now the same function can be specified like this:
val f: Int => String = x => "dude: " + x
scala> f(3)
res31: String = dude: 3
=>
String = x
mean? I thought that when you want to define something in Scala you'd do x:String
?Upvotes: 3
Views: 208
Reputation: 8985
Both Lee and pedrofurla gave excellent answers. I'll also add that if you want your method to be converted to a function (for passing as a parameter, use as a partially applied function, etc), you can use the magic underbar:
def foo(i: Int) = "dude: " + x
val bar = foo _ // now you have a function bar of type Int => String
Upvotes: 3
Reputation: 12783
Only to clarify a bit. def
statements defines methods, not functions.
Now, for the function. You could have written it this way:
val f: (Int => String) = x => "dude: " + x
And it could be read as "f is a function from Int to String". So, answering your question, a =>
in a type position mean function from type to type, while =>
in a value position means takes parameter identifier
and returns expression
.
Further, it can also rely on the type inferrer:
val f = (x:Int) => "dude: " + x
Upvotes: 6
Reputation: 144106
You should parse it as
val (f: Int => String) = (x => "dude: " + x)
So it specifies that f has type (Int => String)
and is defined as an anonymous function which takes an Int
parameter (x)
and returns a String
.
Upvotes: 10