Complexity understanding function syntax
I can figure it out:
scala> def f(i: Int) = "dude: " + i
f: (i: Int)java.lang.String
scala> f(3)
res30: java.lang.String = dude: 3
Defines a function f that takes an int and returns a string of the form dude: + int that is passed.
Now the same function can be set as follows:
val f: Int => String = x => "dude: " + x
scala> f(3)
res31: String = dude: 3
- Why do we need two
=>
- What does it mean
String = x
? I thought that if you wanted to define something in Scala, would you dox:String
?
source to share
Just to clarify a little. Operators def
define methods, not functions.
Now for the function. You could write it like this:
val f: (Int => String) = x => "dude: " + x
And it can be read as "f is a function from Int to String". So, answering your question, =>
in type position means a function from type to type, and =>
in value position means parameter identifier
and returns expression
.
Moreover, it can also rely on the inferrer type:
val f = (x:Int) => "dude: " + x
source to share
Both Lee and Pedrofurla gave excellent answers. I'll also add that if you want your method to be converted to a function (to be passed as a parameter, used as a partially applied function, etc.), you can use the magic subbar:
def foo(i: Int) = "dude: " + x
val bar = foo _ // now you have a function bar of type Int => String
source to share