2017-05-07 123 views
-3

什么是(代码:=>单元)参数在此阶函数来完成从斯卡拉文档:斯卡拉:=>参数

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

Link

+1

不是重复。我怎么知道这个在scala中被称为什么......我从语法的角度来问这个问题。有多少其他用户会有我的问题,并没有找到其他答案... – user3685285

回答

0

=>语法函数的参数列表内意味着该参数本身就是一个函数(称为高阶函数)。那个函数签名说的是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) 
+0

我明白了,但'代码'是一个函数,需要一个'什么',并返回单位?如果是(代码:Int => Unit),这对我有意义 – user3685285

+0

这是不正确的。 'code:=> Unit'是一个名字参数,而不是一个函数。 – puhlen