任何人都可以解釋我這兩種類型的函數定義各不相同。它只是一個語法?或東西是比我大的思維......Scala中的函數定義
方法1種
def incriment(x:Int):Int = x+1
方法2
def incriment=(x:Int) =>x+1
任何人都可以解釋我這兩種類型的函數定義各不相同。它只是一個語法?或東西是比我大的思維......Scala中的函數定義
方法1種
def incriment(x:Int):Int = x+1
方法2
def incriment=(x:Int) =>x+1
這兩個功能是完全不同的。
Re。 1
def incriment(x: Int) : Int = x + 1
這只是一個函數,返回一個Int
。
Re。 2
def incriment = (x: Int) => x+1
def incriment : (Int) => Int = (x:Int) => x+1
這一個是返回函數,它接受一個Int
並返回一個Int
((Int) => Int
)的功能。我已經添加了類型註釋來說明事情。 Scala允許你省略這個,但有時候建議添加它(例如公共方法等)。
斯卡拉REPL是你的朋友,
第一個,簡直是採用INT作爲輸入和返回int作爲返回類型的方法。
scala> def increment1(x:Int): Int = x + 1
increment1: (x: Int)Int
| |
input return type
並且必須被提供的輸入方法,
scala> increment1
<console>:12: error: missing arguments for method increment1;
follow this method with `_' if you want to treat it as a partially applied function
increment1
scala> increment1(89)
res3: Int = 90
第二個,是一個返回功能內搭int和返回int
scala> def increment2 = (x:Int) => x + 1
increment2: Int => Int
| |
func input func return type
//you can pass this function around,
scala> increment2
res5: Int => Int = <function1>
的方法調用一個函數,可以調用apply
方法。
scala> increment2.apply(89)
res7: Int = 90
// or you can simply pass parameter within paren, which will invoke `apply`
scala> increment2(89)
res4: Int = 90
在Scala中,我們可以跳過返回類型,如果類型推斷很簡單。
在第一種方法:
def increment(x: Int) : Int = x + 1
它返回整數的函數(遞增整數參數)
但第二種方法:
def increment = (x:Int) =>x+1
這實際上是返回一個函數另一個功能。 返回的函數可以通過客戶端傳遞整數並獲得遞增的整數作爲響應
'val'也可以用於寫入函數定義,如同'val incr:(Int => Int)=(x:Int )=> x + 1'請注意,此語法預先定義了參數類型和返回類型,然後提供了代碼。 – Paul