2017-11-18 105 views
0

一個簡單函數文本可以被寫爲理解階類型功能

DEF添加(X:強度)= X + 2

在上述例子中我明白添加是一個函數,它接受一個I​​nt和給出一個Int。它的類型是add:(x:Int)Int

這很清楚。

但是下面的例子中,其是式期權[INT] =>內部是有點不清楚

scala> def matchFunction : Option[Int] => Int = { 
    | case Some(x) => x 
    | case None => 0 
    | } 
matchFunction: Option[Int] => Int 

在第二示例中,任何人都可以解釋爲什麼類型應該它不

def matchFunction (x : Option[Int]) : Int 

也請解釋什麼是上述功能並低於所述一個之間的差使用匹配從類型透視

def matchFunction (x : Option[Int]) : Int = x match { 
    case Some(x) => x 
    case None => 0 
} 
+0

'add'是一種方法不起作用。所以你想知道https://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala – chengpohi

+0

@chengpohi,爲什麼要添加一個方法,但matchFunction的一個函數。兩者都是def,那麼爲什麼與另一個不同呢? – Srinivas

+0

'matchFunction'是一個無參數方法,所以你可以像使用變量一樣使用它,並且它返回一個'function'。等於:'def matchFunction():...' – chengpohi

回答

1

基本上這是函數式編程方面之一:高階函數 - 將其他函數作爲參數或者其結果是函數的那些函數。 Option[Int] => Int是以Option[Int]作爲參數並返回Int的匿名函數,匿名函數始終可以使用def,def matchFunction(x : Option[Int]): Int = { ... }表示,def matchFunction(x : Option[Int]): Int = { ... }只是表示Option[Int] => Int = { ... }的另一個變體。高階函數對泛化,多態性很有用。所以你可以將你的matchFunction函數作爲參數來使用Option[Int] => Int函數。 List(Some(1), None, Some(2)).map(matchFunction)會給你List(1, 0, 2)

https://www.scala-exercises.org/scala_tutorial/higher_order_functions

+0

謝謝你的幫助。我現在知道了。 – Srinivas