dublintech
dublintech

Reputation: 17785

Difficulty understanding function syntax

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

Upvotes: 3

Views: 208

Answers (3)

rs_atl
rs_atl

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

pedrofurla
pedrofurla

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

Lee
Lee

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

Related Questions