Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.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,我是斯卡拉的新手。我一直在搜索,但对于我提出的看似简单的问题,没有一个简单的“搜索字符串” def foo( f: (String) => String ){println(f("123"))} foo{_+"abc"} //works def bar( f :() => String ){println(f())} bar{"xyz"} // why does this not work? def baz( f: => String ){println(f)} baz{"

我是斯卡拉的新手。我一直在搜索,但对于我提出的看似简单的问题,没有一个简单的“搜索字符串”

def foo( f: (String) => String ){println(f("123"))}
foo{_+"abc"} //works

def bar( f :() => String ){println(f())}
bar{"xyz"} // why does this not work?

def baz( f: => String ){println(f)}
baz{"xyz"} //works

为什么第二个(
bar
)不起作用?

bar
接受不带参数的函数并返回
字符串。您只给了它一个
字符串
。要使其发挥作用:

bar{() => "xyz"}

第二个
baz
之所以有效,是因为它不是一个函数文本,而是一个按名称调用的参数。基本上,它所做的是将参数计算延迟到程序需要时。你也可以阅读有关这个问题的文章。
对于
bar
您只需要传递一个函数,如
bar{()=>“xyz”}

这种情况对于无参数函数/块是特殊的

object Fs2 {
  def f0=1
  def f0_1()=1
}

object Main extends App {
  println(Fs2.f0)
  //println(Fs2.f0()) wont compile
  println(Fs2.f0_1)
  println(Fs2.f0_1())
}

单元“()”对于f0_1是可选的。将其添加到f0将导致错误。f0不接受任何参数。单元本身是一个声明没有参数的参数。Fs2.f0对应于baz,Fs2.f0()对应于bar。

baz
方法,那么当您想要定义结构时,推荐的方法是
try{…}
?@jfisher实际上在Scala中根本不推荐try-catch。有更多的功能性方法来使用。至于名称调用,当你有一些大的计算机并且你不确定是否需要它时,它是很有用的,例如在if-else表达式中,我的意思是如果我想创建类似的结构,比如
monitor{…}
mutex{…}
instrument{…}
等等。对于这种“语言”结构,“baz”方法是最好的吗?