Scala - What does ' => SomeType' means? [duplicate]

99封情书 提交于 2019-12-20 18:42:45

问题


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!


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7225308/scala-what-does-sometype-means

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!