简体   繁体   English

Scala如何发送匿名函数结果作为参数

[英]Scala How To Send Anonymous Functions Results as Argument

How does one send the result of an anonymous function as an argument into another function? 一个人如何将匿名函数的结果作为参数发送给另一个函数?

As an example: 举个例子:

object TestThisFunction {

  def getString(): String = {
    "foo"
  }

  def useString(foo: String) = {
      println(foo + "bar")
  }

  useString("foo");
  useString(getString());

  // This does not work: type mismatch; found : () => String required: String
  useString(() => {
    "foo"  
  })
}

Is there some syntax that would make the last call to useString() work using an anonymous function? 是否有一些语法可以使用匿名函数使对useString()的最后一次调用起作用?

Thank you for your time. 感谢您的时间。

Call the anonymous function immediately after creating it, to have it's evaluated value be used, instead of the function itself: 创建匿名函数后立即调用它,以使用其评估值代替函数本身:

useString((() => {
  "foo"  
})())

You can also pass in arguments, if needed: 您还可以根据需要传递参数:

scala> ((a: String) => { a })("bar")
res3: String = bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM