Scala:=>;参数

Scala:=>;参数,scala,Scala,scala文档中的(code:=>Unit)参数在这个scala函数中起什么作用: def unless(exp: Boolean)(code: => Unit): Unit = if (!exp) code unless(x < 5) { println("x was not less than five") } def除非(exp:Boolean)(code:=>Unit):Unit=if(!exp)代码 除非(x语法意味着该参数本身就是一个函数(称为高阶函数)。这个函数签

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

def unless(exp: Boolean)(code: => Unit): Unit = if (!exp) code
unless(x < 5) {
  println("x was not less than five")
}
def除非(exp:Boolean)(code:=>Unit):Unit=if(!exp)代码
除非(x<5){
println(“x不小于5”)
}

函数参数列表中的
=>
语法意味着该参数本身就是一个函数(称为高阶函数)。这个函数签名的意思是
,除非
是一个接受布尔值的函数,并且接受一个不接受参数并返回
单位的函数。以下是更多的例子:

// 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)

不是复制品。我怎么知道这在scala中叫什么…我是从语法的角度问的。有多少其他用户会有我的问题而找不到其他答案……我明白了,但“代码”是一个接受“what”并返回单位的函数?如果它是(code:Int=>Unit),这对我来说是有意义的。这是不正确的<代码>代码:=>单位
是按名称参数,不是函数。