scala 函数中嵌套函数_如何在Scala中将函数转换为部分函数?
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!=0def 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!=0def 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 函數中嵌套函數
總結
以上是生活随笔為你收集整理的scala 函数中嵌套函数_如何在Scala中将函数转换为部分函数?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java LineNumberReade
- 下一篇: 2万字!66道并发面试题及答案