Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 此部分应用的函数尝试有什么问题?_Scala - Fatal编程技术网

Scala 此部分应用的函数尝试有什么问题?

Scala 此部分应用的函数尝试有什么问题?,scala,Scala,我正在尝试编写一个部分应用的函数。我原以为下面的方法行得通,但行不通。谢谢你的帮助 scala> def doSth(f: => Unit) { f } doSth: (f: => Unit)Unit scala> def sth() = { println ("Hi there") } sth: ()Unit scala> doSth(sth) Hi there scala> val b = sth _ b: () => Unit = <f

我正在尝试编写一个部分应用的函数。我原以为下面的方法行得通,但行不通。谢谢你的帮助

scala> def doSth(f: => Unit) { f }
doSth: (f: => Unit)Unit

scala> def sth() = { println ("Hi there") }
sth: ()Unit

scala> doSth(sth)
Hi there

scala> val b = sth _
b: () => Unit = <function0>

scala> doSth(b)
<console>:11: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
              doSth(b)
                    ^
scala>def doSth(f:=>Unit){f}
doSth:(f:=>单位)单位
scala>def sth()={println(“你好”)}
某物:()单位
(某物)
你好
scala>valb=sth_
b:()=>单位=
scala>doSth(b)
:11:警告:纯表达式在语句位置不起任何作用;您可能省略了必要的括号
多斯(b)
^

谢谢

差别很小
sth
是一个方法,因此您可以在不使用括号的情况下调用它,这里就是这样:

doSth(sth)
但是
b
只是一个函数
()=>单元
,您必须使用括号来调用它

doSth(b())
否则,您将无法将
b
分配给另一个标识符

val c: () => Unit = b
如果我们在这里自动调用
b
c
将是
Unit
,而不是
()=>Unit
。必须消除歧义


我还要澄清的是,
doSth
不是一种只接受函数的方法
f:=>Unit
表示它接受任何计算结果为
Unit
的内容,包括调用时返回
Unit
的方法
doSth(sth)
不是将消息
sth
传递给
doSth
,而是调用
sth
,不带括号并传递结果。

我认为区别在于
b
具有类型
()=>单位
,而
doSth
需要一个返回
单位
的表达式(细微区别)。如果您想将
sth
存储为无副作用的变量,可以执行以下操作:

lazy val b = sth
doSth(b)
另一个选项是将其设置为使
doSth
接收
()=>单元

def doSth(f: () => Unit) { f() }
def sth() = { println ("Hi there") }
doSth(sth)
val b = sth _
doSth(b)

对不起,我认为你是不对的。我将doth定义为一个接受函数的方法。当我将某事物传递给它时,是doSth在其功能体中执行某事物。您可以通过将doSth更改为def-doSth(f:=>Unit){println(“此处优先”);f}来证明这一点。它将先打印“此处优先”,然后打印“Hi-there”。我尝试执行doSth(b),因为我希望它传递b,一个部分应用的函数,以便执行。根据scala中的编程,您可以通过这种方式传递部分应用的函数(我认为),但我无法让它工作。
f:=>Unit
与返回
Unit
的函数不同。它是产生
单位
作为值的任何东西。例如,我可以调用
doSth(Unit)
,但我没有传递函数,是吗?啊,1000谢谢,并为你的错误道歉。我完全不知道f:=>单位是什么。我认为这就像你可以不使用()这个无参数方法一样。啊,这就解释了一切。。再次感谢。非常感谢。。