【问题标题】:Scala : => parameters [duplicate]斯卡拉:=>参数[重复]
【发布时间】:2017-10-05 06:16:24
【问题描述】:

scala 文档中的 (code: => Unit) 参数在这个 scala 函数中做了什么:

def unless(exp: Boolean)(code: => Unit): Unit = if (!exp) code
unless(x < 5) {
  println("x was not less than five")
}

Link

【问题讨论】:

  • 不是重复的。我怎么应该知道这在 scala 中被称为什么......我从语法的角度询问它。有多少其他用户有我的问题却找不到其他答案...

标签: scala


【解决方案1】:

函数参数列表中的=&gt; 语法意味着该参数本身就是一个函数(称为高阶函数)。该函数签名的意思是unless 是一个接受布尔值的函数,并接受一个不接受参数并返回Unit 的函数。以下是更多示例:

// This is a function that takes as a parameter that is a function that takes an Int, and returns a Boolean
def foobar(f: Int => Boolean) = ???

// It might be called like this:
foobar(i => i / 2 == 0)

// Which is the same as this
def isEven(i: Int): Boolean = {
  i / 2 == 0
}
foobar(isEven)

【讨论】:

  • 我明白了,但“代码”是一个接受“什么”并返回单位的函数?如果是这样对我来说是有意义的(代码:Int => Unit)
  • 这是不正确的。 code: =&gt; Unit 是一个名称参数,而不是一个函数。
猜你喜欢
  • 1970-01-01
  • 2011-09-16
  • 2013-11-23
  • 2019-08-28
  • 2016-01-31
  • 2017-10-23
  • 1970-01-01
  • 2014-06-15
  • 1970-01-01
相关资源
最近更新 更多