Scala - What does ' => SomeType' means? [duplicate]
Today I would like to ask what does the => SomeType
mean. I found it used in this article. It's in the part 'The Sequential Combinator'.
Thanks for any answer!
It means a block of code that you can run.
So for example:
scala> def doTwice(op: =>Unit) = {op; op}
doTwice: (op: => Unit)Unit
scala> doTwice({println("Hi")})
Hi
Hi
In this case the =>Unit
is {println("Hi")}
Here "SomeType" is Unit because println
doesn't produce a value. If it produced an Int
, it would be =>Int
.
It indicates two things. First, because of the prefixing =>
, it indicates the parameter will be passed by name. Then, it indicates the type of the parameter passed must be SomeType
.
Some people conflate the two, thinking => SomeType
is a type itself -- it isn't. It's a conjunction of two things: parameter evaluation strategy and parameter type.
So, brief explanation on call by name, in case the wikipedia link didn't make things clear, if you have this:
def f[A](x: => A) = { x; x }
f(some stuff)
Then Scala will execute this like this:
{ some stuff; some stuff }
On a call by value, what happens is more like this:
val x = some stuff
{ x; x }
Note also that the parameter is always evaluated on call by value, but only once. On call by name, the parameter may never be evaluated (if it's on a non-executing branch of an if
, for instance), but may be evaluated many times.
It's just a type of a function value that takes no parameters. Owen's example is cool, just know that "A => B" is a function with a parameter that has type A and return-value with type B and "=> B" is a function that takes no parameters and returns a value with type B.
精彩评论