scala 函数中嵌套函数
First, let's see what is a function and a partial function, and then we will see their conversion process.
首先,让我们看看什么是函数和部分函数,然后看它们的转换过程。
Function in Scala is a block of code that is used to perform a specific task. Using a function you can name this block of code and reuse it when you need it.
Scala中的Function是用于执行特定任务的代码块。 您可以使用函数来命名此代码块,并在需要时重新使用它。
Example:
例:
def divide100(a : Int) : Int = {
return 100/a;
}
Partial function in Scala are functions that return values only for a specific set of values i.e. this function is not able to return values for some input values.
Scala中的部分函数是仅返回特定值集的值的函数,即该函数无法返回某些输入值的值。
Example:
例:
def divide100 = new PartialFunction[Int , Int] {
def isDefinedAt(a : Int) = a!=0
def apply(a: Int) = 100/a
}
将函数转换为部分函数 (Convert function to partial function)
You can replace a function with a partial function as the definition of the function cannot be changed by we will call the given function using our partial function which will convert the function to function.
您可以将函数替换为部分函数,因为函数的定义无法更改,因为我们将使用部分函数调用给定函数,这会将函数转换为函数。
Scala程序将功能转换为部分功能 (Scala Program to convert function to partial function)
//Convert function to partial function
object MyClass {
def divide100(x:Int) = 100/x;
def dividePar = new PartialFunction[Int , Int] {
def isDefinedAt(a : Int) = a!=0
def apply(a: Int) = divide100(a)
}
def main(args: Array[String]) {
print("100 divided by the number is " + dividePar(20));
}
}
Output:
输出:
100 divided by the number is 5
翻译自: https://www.includehelp.com/scala/convert-function-to-partial-function-in-scala.aspx
scala 函数中嵌套函数